0

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.

1
  • 1
    Also it is usually a good habit to have your code and your output synchronized. You're saying that you have TestShow in your output, but you do not have it in your code. Commented Jul 19, 2011 at 14:37

3 Answers 3

3

You wrote f1 = f.

Therefore, you are calling f.

Sign up to request clarification or add additional context in comments.

Comments

0
f1 = f; 

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.