I am developing a C# .NET 2.0 application wherein at run-time one of two DLLs are loaded depending on the environment. Both DLLs contain the same functions, but they are not linked to the same address-offset. My question is regarding the function delegates in my application code.
public class MyClass
{
public delegate int MyFunctionDelegate(int _some, string _args);
public MyFunctionDelegate MyFuncToCallFrmApp;
public MyClass() : base()
{
this.MyFuncToCallFrmApp = new MyFunctionDelegate(this.MyFuncToCallFrmApp); // <-- Exception thrown here.
}
public SomeFunction()
{
MyFuncToCallFrmApp(int _someOther, string _argsLocal);
}
}
When my code executes I get an ArgumentException
of "Delegate to an instance method cannot have null 'this'." What am I doing wrong?
Jim, I'm trying to learn delegates in C# myself.
One problem with your code is that you have not assigned the delegate to a valid handler. The signature of the delegate has to be matched to a valid handler with the same method signature.
In the line:
this.MyFuncToCallFrmApp
is a delegate, but it needs to be a valid method handler instead.Here is how you pass in a method handler:
Hopefully the link below and sample code will be of some help to you:
Delegates Tutorial
You're trying to initialize the delegate to call itself. What you're doing fundamentally doesn't make sense.
You're trying to create a new instance of a delegate using the uninitialized instance of the delegate that is already in your class...which makes no sense.
You need to initialize the delegate using a method from your class that has a matching arguments list as your delegate or don't initialize the delegate and allow the consumer of your class to initialize the delegate using a matching method from their code (which is what delegates are normally used for):
You need to assign a valid function (hosted by some class in the dynamically loaded dll) to your delegate variable. If the functions are static methods on classes with the same name, this is straightforward:
If the functions are instance methods of classes with the same name, just create an instance and do the same thing (also note that as long as the delegate is in scope, it will prevent the
ExternalClass
instance from being garbage-collected - you may want to store the instance as a member variable to make that clearer):If the dynamically-loaded classes have different names, you'll need to determine which one to call - in this example, I'm using a boolean member variable to decide whether or not to use a default assembly's class:
In your line:
You are using "this.MyFuncToCallFrmApp" before you are assigning it, which means it is null during the time of assignment. Making a delegate point to itself makes no sense. Is that what you are trying to do?