gkhan
gkhan

Reputation: 47

instantiate and initalialize the delegate

I have a quick question about coding delegates.

Why do you have to

pf = t.Print;  //instantiate and initialize the delegate.

code

delegate void PrintFunction();

    public class Test
    {
        public void Print()
        {
            Console.WriteLine("Print 1 --instance");
        }

        public static void Print1()
        {
            Console.WriteLine("Print 2 -- static");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            PrintFunction pf;
            pf = t.Print;  //instantiate and intialize the delegate

            pf += Test.Print1;
            pf += t.Print;


            if (null != pf)
            {
                pf();
            }
            else
                Console.WriteLine("delegate is empty");
        }
    }
}

Upvotes: 1

Views: 884

Answers (4)

Zein Makki
Zein Makki

Reputation: 30022

Delegates are immutable reference types, their default value is null. The default constructor for the delegate accepts a method that matches its signature.

So you can do this:

var pf = new PrintFunction(Test.Print1);
pf += t.Print;

Or:

var pf = Test.Print1;
pf += t.Print;

Or:

var pf = null;
pf += Test.Print1;
pf += t.Print;

Edit:

Source that Delegates are reference types: MSDN

A reference type contains a pointer to another memory location that holds the data. Reference types include the following:

  • String.
  • All arrays, even if their elements are value types
  • Class types, such as Form
  • Delegates

Upvotes: 3

gkhan
gkhan

Reputation: 47

so you have to initialize the delegate the first before you call it, like when calling a class. Also the delegate signature has to match the method that is calling the delegate.

Thanks everyone for the help. Should of coped it before i posted the question.

Thanks again.

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117057

You do not have to call the code pf = t.Print;. It is perfectly acceptable to write pf = null;.

If you remove the line pf = t.Print; you'll just discover that the compiler is giving you the error "CS0165 Use of unassigned local variable 'pf'".

This is no different than if you wrote the code:

bool flag;

if (flag)
{
}

It's nothing to do with it being a delegate. It's just a compiler error.

Upvotes: 0

Patrios
Patrios

Reputation: 66

By default delegate value is null you should initialize it to something and then use it or add other methods. In your sample there will be 2 times called t.Print and one time Test.Print1.

Good practice is to initialuize delegate to nullable object and then use it without any null checking like below.

PrintFunction pf = () => {};
pf += Print1;
pf += Print;
pf += Print1;
pf();

Upvotes: -1

Related Questions