Default value of delegates inside classes

2019-07-15 07:36发布

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!

标签: c# delegates
1条回答
Animai°情兽
2楼-- · 2019-07-15 08:17

Delegates are reference types, so the default value is null.

However, variables (unlike fields) are not initialized by default:

Printer p;
p += myPrint; // doesn't work: uninitialized variable

You need to initialize the variable before you can use it:

Printer p = null;
p += myPrint;

or

Printer p;
p = null;
p += myPrint;

Note that for delegates (but not events!)

p += myPrint;

is shorthand for

p = (Printer)Delegate.Combine(p, new Printer(myPrint));
查看更多
登录 后发表回答