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?
Partial classes are different parts of the same class and so they can have only one constructor.
A partial class is a special feature of C#. It provides a special ability to implement the functionality of a single class into multiple files and all these files are combined into a single class file when the application is compiled. A partial class is created by using a partial keyword.
Partial Class is a unique feature of C#. It can break the functionality of a single class into many files. When the application is compiled, these files are then reassembled into a single class file. The partial keyword is used to build a partial class.
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public , private , and so on.
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 */ } }
Search for "partial methods". They will do exactly what you want.
For example:
public partial class Test { public Test() { //do stuff DoExtraStuff(); } partial void DoExtraStuff(); } public partial class Test // in some other file { partial void DoExtraStuff() { // do more stuff } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With