Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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...

  • Using generics?
  • Telling somewhere a posteriori that NP1.AAA and NP2.AAA implement a common interface? Something like using partial classes and appending the interface information in a latter stage, but I can't modify the autogenerated files.
  • ...?
like image 774
xavier Avatar asked Sep 12 '25 19:09

xavier


1 Answers

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.

like image 76
Blindy Avatar answered Sep 14 '25 09:09

Blindy