First of all, “A group of methods is a set of overloaded methods obtained as a result of an element search”. In my example, I use the Console.WriteLine method set with 19 overloads.
The definition of a group of methods in the C # Language Specification also states that: "A group of methods is allowed in a call expression (§7.6.5), create-delegate expression (§7.6.10.5) and how the left side of a is and can be implicitly converted to a compatible delegate type (§6.6). "
I might think of one scenario where this functionality might be useful:
Action<string> print = (Action<string>)Console.WriteLine; print("Hello!"); if (Console.WriteLine is Action<string>) { Console.WriteLine("We're compatible!"); }
The first couple of lines shows that we can "pass a group of Console.WriteLine methods to a delegate. Actually, an" implicit conversion is converted to a compatible delegate type "that creates an instance of a delegate that calls one of the many overloaded Console.WriteLine methods with a compatible signature .
Thus, according to the specifications, we could use the “operator left side” function mentioned above to check if a group of methods is compatible with this type of delegation (there is an implicit conversion). This is what is checked inside the if if statement in the sample code.
Surprisingly, the code compiles, but gives the warning "This expression never refers to the type provided (" System.Action ")." Thus, it seems that there will be no attempt to verify the compatibility of the method group and delegate type at run time.
Therefore, my questions are:
- Why are the groups of methods allowed on the left side of 'is statements if the check cannot be performed at run time?
- Why does this construct give a warning rather than a compilation error?
- Are there practical scenarios for using method groups on the left side of the is statement?
- Is this something reserved for future use, i.e. is it supposed that the code above will work someday?
methods c # delegates
Nicol eye
source share