Why are ref parameters not contravariant?

It works:

EndPoint endPoint = new IPEndPoint(_address, _port); _socket.ReceiveFrom(buffer, 0, 1024, SocketFlags.None, ref endPoint); 

But this is not so:

 IPEndPoint endPoint = new IPEndPoint(_address, _port); _socket.ReceiveFrom(buffer, 0, 1024, SocketFlags.None, ref endPoint); 

(Note the type of endPoint)

Which seems strange. Why does the ref keyword drag the contravariance parameter?

+4
source share
2 answers

Because in the method signature, the endPoint parameter is declared as endPoint , not IPEndPoint ; there is no guarantee that the method will not set endPoint to another type of endPoint that will not be assigned to the IPEndPoint variable.

For example, suppose you have a FooEndPoint class that inherits from endPoint , and a Foo method that accepts the ref EndPoint :

 public class FooEndPoint : EndPoint { ... } public void Foo(ref EndPoint endPoint) { ... endPoint = new FooEndPoint(); ... } 

If you were able to pass IPEndPoint this method, then the FooEndPoint parameter to the endPoint parameter will fail at runtime because FooEndPoint not IPEndPoint

+17
source

Because the ReceiveFrom method can create a new EndPoint, but not IPEndPoint. This parameter works in two directions, so the type must match exactly.

+2
source

All Articles