views:

71

answers:

3

I have a constructor that is in generated code. I don't want to change the generated code (cause it would get overwritten when I regenerate), but I need to add some functionality to the constructor.

Here is some example code:

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

The only solution I can come up with is this:

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

I am fairly sure this will work, but I then have a lame unused param to my constructors and I have to go change them all. Is there a better way? If not that is fine, but I thought I would ask.

+2  A: 

If you're using 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
   }
}
Jon Skeet
Alas, this is code generated from a WSDL. I have no idea how to change that generator.
Vaccano
Darn... if you can't change the generator, you can't do a lot, unfortunately. You could derive a new class from the generated one, but I tend to view that as a bit of an abuse of inheritance. You can add other constructors of course - but if you don't *need* any extra parameters, it's a bit of a pain. How about adding a static method which calls the constructor and then calls something else?
Jon Skeet
+1  A: 

Would your environment allow you to inherit from MyGeneratedClass rather than have it as a partial class. You could then override the constructor?

ArtificialGold
+1  A: 

Assuming you can't change the generator output, unfortunately, your options are a bit limited, and not ideal considering what you're looking for. They are:

  • Inherit from the generated class. The child class will implicitly call the parent's construtor.
  • Use a static method as an initializer
Daniel Schaffer