xavier
xavier

Reputation: 2040

C# How to use 2 classes with the same properties without modifying them

I have two identical classes in different namespaces:

namespace NP1 {
   public class AAA {
      public int A {get; set;}
      public int B {get; set;}
   }
}

namespace NP2 {
   public class AAA {
      public int A {get; set;}
      public int B {get; set;}
   }
}

They are in different files and they are autogenerated. I can't modify them.

Then I have two other files:

using NP1;

public class N1Helper {
   (...)
   var sth = new AAA(A: some_value, B: some_other_value);
   (...)
}

and

using NP2;

public class N2Helper {
   (...)
   var sth = new AAA(A: some_value, B: some_other_value);
   (...)
}

The skipped parts of these helpers are identical.

I'd like to simplify these two files and write the code only once. If the classes in these namespaces would implement an interface, I could do it.

Is there a way I can solve this problem...

Upvotes: 3

Views: 222

Answers (2)

clamchoda
clamchoda

Reputation: 4941

As Blindy mentioned you wont be able to make use of the generic type because it doesn't implement any interfaces. Although you could use the type to identify the context while taking advantage of dynamic to access/return the properties and methods in a common manner.

public class NHelper<TAAA>
{
    public dynamic GetSth(int some_value, int some_other_value)
    {
        dynamic someclass = typeof(TAAA) == typeof(NP1.AAA) ? new NP1.AAA() : new NP2.AAA();

        someclass.A = some_value;
        someclass.B = some_other_value;

        return someclass;
    }
}

I'm not sure what 'sth' is I just followed your naming convention.

NHelper<NP1.AAA> helper = new NHelper<NP1.AAA>();
dynamic test = helper.GetSth(1, 2);
int A = test.A;
int B = test.B;
//int calc = test.Calculate();


NHelper<NP2.AAA> helper2 = new NHelper<NP2.AAA>();
dynamic test2 = helper2.GetSth(1, 2);
A = test2.A;
B = test2.B;
//calc = test2.Calculate();

Upvotes: 1

Blindy
Blindy

Reputation: 67352

Using generics

Sure, just take the type as a generic argument. You just won't be able to actually use the generic argument, because it doesn't implement any interfaces:

public class NHelper<TAAA> {
   (...)
   // this is not going to work
   // var sth = new TAAA(A: some_value, B: some_other_value);
   (...)
}

using partial classes [...] I can't modify the autogenerated files

Partial classes have to have the partial keyword, and your auto-generated classes don't. So no.

...?

Same no. C# isn't a duck-typing language like C++, it's a strongly typed language at every layer. You get exactly what you code, and if you don't feel like coding, you won't get anything.

Fix your auto-generated files.

Upvotes: 4

Related Questions