I have a delegate
delegate void Del(int a, int b);
why does this code works:
class MyClass
{
private Del invoker;
public void SetInvoker(Del del)
{
invoker += del; //everything is ok
}
}
while this code doesn't?
public class Program
{
static void Main(string[] args)
{
Del invoker += new Del(Display); //error! Invalid expression term '+='
}
static void Display(int a, int b)
{
}
}
it's pretty strange because in both cases invoker is null before initializing (before using += operator)
This line
Del invoker += new Del(Display);
is equal to
Del invoker;
invoker = invoker + new Del(Display);
Where the invoker can't be used in + operator because it is not initialized.
So
In the Main method your invoker is a local variable and every local variable must be initialized before using. invoker's value is not null, but it is not initialized. If you doesn't assign any value to the variable, it will throw you an error, that it is not initialized. So you need to explicitly assign null to it.
public class Program
{
static void Main(string[] args)
{
Del invoker = null;
invoker += new Del(Display); //error!
}
static void Display(int a, int b)
{
}
}
When you use the class version, class'es constructor will initialize the fields for first with their default values. So after the object creation, all it's fields have default values and so you can use += with them.
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