Are method names implicitly applied to delegate types?

I have a little problem understanding delegates.

I have a delegate that I will call when I enter the y character:

public delegate void respondToY(string msgToSend); private respondToY yHandler; 

I have a subscription method so that the calling code can request a notification when a delegate is called:

 public void Subscribe(respondToY methodName) { yHandler += methodName; } 

As far as I can see, in order to register with this delegate, I need to provide something like responseToY. However, when I call the subscription method, I can provide either a new delegate instance or just the name of the method. Does this mean that any method that matches the signature of the delegate can be used and will be automatically converted to the correct delegate type?

** Change **

Thus, under this assumption, it would be fair to specify only the name of the method for such things as click event handlers for buttons (assuming the method took the sender and the corresponding event object), will it be converted to the required delegate?

+8
c # delegates
source share
2 answers

This is a transformation of a group of methods. It converts a group of methods (mainly a method name or overloaded methods) into an instance of a delegate type with a compatible signature.

Yes, any compatible method can be used. Please note that you can also specify a goal:

 string text = "Hello there"; Func<int, int, string> func = text.Substring; Console.WriteLine(func(2, 3)); // Prints "llo", which is text.Substring(2, 3) 

There must be a specific type of delegate. You cannot just use:

 Delegate x = methodName; 

... the compiler does not know the type of delegate to create.

See section 6.6 of the C # 4 Language Specification for more information.

Note that the transformation of a group of methods always creates a new instance of this delegate - it is not cached (and cannot be without breaking the specification).

+9
source share

as far as I know ... yes, the type of delegate just guarantees signature matching

+2
source share

All Articles