C # - adding to an existing (generated) constructor

I have a constructor that is in the generated code. I do not want to modify the generated code (because it will be overwritten during recovery), but I need to add some functionality to the constructor.

Here is a sample code:

// Generated file public partial class MyGeneratedClass { public MyGeneratedClass() { Does some generated stuff } } 

The only solution I can come up with is the following:

 // My hand made file public partial class MyGeneratedClass { public MyGeneratedClass(bool useOtherConstructor):this() { do my added functinallity } } 

I'm sure this will work, but I have a lame unused parameter for my designers, and I have to change them all. Is there a better way? If not everything is fine, but I thought I would ask.

+4
source share
3 answers

If you use C # 3 and can change the generator, you can use partial methods :

 // MyGeneratedClass.Generated.cs public partial class MyGeneratedClass { public MyGeneratedClass() { // Does some generated stuff OnConstructorEnd(); } partial void OnConstructorEnd(); } // MyGeneratedClass.cs public partial class MyGeneratedClass { partial void OnConstructorEnd() { // Do stuff here } } 
+2
source

Will your environment allow you to inherit from MyGeneratedClass, and not have it as a partial class. Could you then override the constructor?

+1
source

Assuming you cannot change the output of the generator, unfortunately your options are a bit limited and not ideal, considering what you are looking for. It:

  • Inherit from the generated class. The child class will implicitly call the parent constructor.
  • Use static method as initializer
+1
source

Source: https://habr.com/ru/post/1308679/


All Articles