Is there a way to have a partial class' constructor call another method that my or may not be defined?
Basically my partial class constructor is defined:
public partial class Test
{
public Test()
{
//do stuff
}
}
I would like to be able to somehow insert extra code to be run after the class constructor is called.
In addition, is there a way to have more than one file to inject extra code after the constructor is called?
C# does support the feature of partial methods. These allow a partial class definition to forward declare a method that another part of the partial class can then optionally define.
Partial methods have some restrictions:
Partial methods are implicitly sealed and private.
It is not, however, possible, to have two different portions of a partial class implement the same partial method. Generally partial methods are used in code-generated partial classes as a way of allowing the non-generated part of extend or customize the behavior of the portion that is generated (or sometimes vice versa). If a partial method is declared but not implemented in any class part, the compiler will automatically eliminate any calls to it.
Here's a code sample:
public partial class PartialTestClass
{
partial void DoSomething();
public PartialTestClass() { DoSomething(); }
}
public partial class PartialTestClass
{
partial void DoSomething() { /* code here */ }
}