Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate to an instance method cannot have null 'this'

Say I have a class declared as follows:

public class ExampleClass 
{
   public Action<int> Do { get; set; }

   public ExampleClass()
   {
   }

   public void FuncA(int n)
   {
       //irrelevant code here
   }

   public void FuncB(int n)
   {
       //other irrelevant code here
   }
}

I want to be able to use this class like this

ExampleClass excl = new ExampleClass() { Do = FuncA }

or

ExampleClass excl = new ExampleClass() { Do = excl.FuncA }

or

ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }

I can compile the second option there, but I get a "Delegate to an instance method cannot have null 'this'." exception when I hit that code. The third one doesn't even make sense, because FuncA isn't static.

In my actual code, there will be maybe 10-15 different functions it could get tied to, and I could be adding or removing them at any time, so I don't want to have to have a large switch or it-else statement. Additionally, being able assign a value to 'Do' when instantiating the class is very convenient.

Am I just using incorrect syntax? Is there a better way to create a class and assign an action in one line? Should I just man up and manage a huge switch statement?


1 Answers

You have to create the instance of the class and later set the property to the instance member. Something like:

ExampleClass excl = new ExampleClass();
excl.Do = excl.FuncA;

For your line:

ExampleClass excl = new ExampleClass() { Do = FuncA }

FuncA is not visible without an instance of the class.

For:

ExampleClass excl = new ExampleClass() { Do = excl.FuncA }

Instance has not yet been created that is why you are getting the exception for null reference.

For:

ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }

FuncA is not a static method, you can't access it with the class name.

like image 118
Habib Avatar answered Jul 24 '26 09:07

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!