Rich Porter
Rich Porter

Reputation: 213

Delegates question - Basic

Alright, I have the following code: (copied from my book).

class MyDelegate
{
    public delegate void Func(string s);
    public void Show(string s)
    {
        Console.WriteLine("In MyD1: " + s);
    }
}
class Test
{
    static void Show(string s)
    {
        Console.WriteLine("In test: " + s);
    }
    static void Main(string[] args)
    {
        MyDelegate md = new MyDelegate();
        MyDelegate.Func f= new MyDelegate.Func(md.Show);
        MyDelegate.Func f1= new MyDelegate.Func(Show);
        f("hello");
        f1("Hello");
        f1 = f;
        f1("world");
    }
}

The output is: In MyD1: hello In TestShow Hello InMyD1: world

Now, I didn't understand why the last line of the output is in "InMyD1" . because f1 delegate is called and not f.

Thanks in advance.

Upvotes: 0

Views: 76

Answers (3)

CassOnMars
CassOnMars

Reputation: 6181

f1 is being reassigned the function reference of f. Likewise, if you just assigned it another function in place, such as:

f1 = s => Console.WriteLine("Another function: " + s);

You'd get other output.

Upvotes: 0

raym0nd
raym0nd

Reputation: 3262

f1 = f;

This sets f1 to f thats why you have world instead of Hello

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You wrote f1 = f.

Therefore, you are calling f.

Upvotes: 3

Related Questions