using System;
public delegate void Printer(string s);
class Program
{
public static void Main(string[] args)
{
Printer p = new Printer(delegate {});
p+= myPrint;
p("Hello");
Console.ReadKey(true);
}
public static void myPrint(string s)
{
System.Console.WriteLine(s);
}
}
It seems as if I have to initialize a delegate with an empty anonymous function to be able to use +=
later on. When I omit the new
clause, p
gets to be null
and +=
doesn't work, which makes sense.
Now, when I have a class with a delegate instance, I can do the following:
using System;
public delegate void Printer(string s);
class Program
{
public static void Main(string[] args)
{
A a = new A();
a.p += myPrint;
a.p("Hello");
Console.ReadKey(true);
}
public static void myPrint(string s)
{
System.Console.WriteLine(s);
}
}
class A {
public Printer p;
}
Why is this allowed? Is there a default value for the delegate instance p
? It can't be null
because then I would not be able to assign it a new callback using +=
. I have tried to search for this problem with the keywords "default value for delegates"
and found nothing. Also, sorry if the question if too basic.
Thanks for your help!
Delegates are reference types, so the default value is
null
.However, variables (unlike fields) are not initialized by default:
You need to initialize the variable before you can use it:
or
Note that for delegates (but not events!)
is shorthand for