Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covariance, delegates and generic type constraints [duplicate]

public void Foo<T>(Func<T> bar)
 where T: IMyInterface
{
   Func<IMyInterface> func = bar;
}

It has been a while since I'd understood covariance, but shouldn't this compile?

Anything bar can return is also an IMyInterface. What seems to be the problem?

like image 488
TDaver Avatar asked Apr 16 '12 12:04

TDaver


People also ask

What is covariance and contravariance in generics?

Covariance and contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.

Which delegates support covariance and contravariance in C#?

In . NET Framework 4 and later versions, C# supports covariance and contravariance in generic interfaces and delegates and allows for implicit conversion of generic type parameters.

What is the difference between covariance and contravariance in C#?

Covariance permits a method to have a return type that is a subtype of the one defined in the delegate. Contravariance permits a method to have a parameter type that is a base type of the one defined in the delegate type.

What is generic type constraint?

A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)


1 Answers

Is this a covariance bug in C# 4?

the correct code is:

public void Foo<T>(Func<T> bar)
 where T: class, IMyInterface
{
   Func<IMyInterface> func = bar;
}
like image 61
TDaver Avatar answered Sep 30 '22 11:09

TDaver