Same Signature Delegates

My question is a bit like this: How do I convert an action to a specific delegate of the same signature?

Why is there no implicit conversion between delegates with the same signature. For example, the code:

class Program { private delegate void Foo1(int x); private delegate void Foo2(int x); static void Main(string[] args) { Foo1 foo1 = Console.WriteLine; Foo2 foo2 = Console.WriteLine; Call(foo1); Call2(foo2); } static void Call(Action<int> action) { action(10); } static void Call2(Foo1 action) { action(10); } } 

it does not compile because there isn't implicit convertion from Action<int> to Foo1. But fine, it's the same thing. Thus, this means that these names are aliases and not real names. So I think it was great to think of it as aliases. So, in this case we have 3 aliases a delegate, that get one int value and returns nothing . And these delegates are completely interchangeable one after another. But we don’t have it. So the question is: why? Signatures are the same thing, and there is no implementation, so delegates with the same signature are the same thing with many aliases ...

Is it a C # defect or is there a reason for this? As for me, I do not see.

+4
source share
1 answer

There is no implicit conversion between the two delegates for the same reason that there is no implicit conversion between the two types:

 public sealed class Foo1 { public string Value { get; set; } } public sealed class Foo2 { public string Value { get; set; } } 

Just because two classes have the same fields, this does not mean that you should be able to treat it as if it were different. The same logic applies to delegates (which also apply to types, mind you).

There is a semantic meaning applied to the creation of this type. If someone created Foo1 , he wants him to be Foo1 , not Foo2 . If they do not want to use Foo1 , where Foo2 is expected, this is a big red flag, which, although the types are similar, is the semantic difference between the two types. If a programmer knows something that is not in the compiler, he can use an explicit conversion of some kind to indicate that they know what they are doing.

(The preceding paragraph was intentionally written to apply your delegates and the classes mentioned above equally).

+2
source

Source: https://habr.com/ru/post/1498482/


All Articles