Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of delegates inside classes

Tags:

c#

delegates

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!

like image 974
Kalevi Avatar asked Dec 21 '25 23:12

Kalevi


1 Answers

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));
like image 125
dtb Avatar answered Dec 24 '25 12:12

dtb



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!