Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting constrained generic class in C#

Quite simply, why does this code fail to compile?

public interface IWorld { }
public class Foo<T> where T : IWorld { }
public void Hello<T>(T t) where T : IWorld
{
    Foo<IWorld> bar1 = new Foo<T>(); //fails implicit cast
    Foo<IWorld> bar2 = (Foo<IWorld>)new Foo<T>(); //fails explicit cast
}

Since every T implements IWorld, every instance of Foo<T> should match Foo<IWorld>. Why not? Is there any way around this? I really don't want to resort to generics to accomplish this.

like image 334
Allan Rempel Avatar asked Dec 21 '12 10:12

Allan Rempel


People also ask

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.)

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.

How do you add a generic constraint?

You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.

What is generic class in C sharp?

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.


2 Answers

T : IWorld

means that T has been implemented IWorld and does not mean that it ONLY has implemented IWorld and EXACTLY is IWorld. It may also has been implemented other interfaces.

However, C# supports this cast in it's later versions. Please see http://msdn.microsoft.com/en-us/library/dd799517.aspx (Covariance and Contravariance in Generics)

like image 195
Yasser Zamani Avatar answered Sep 30 '22 17:09

Yasser Zamani


You can cast to object first

Foo<IWorld> bar2 = (Foo<IWorld>)(object)new Foo<T>();
like image 40
Sergey Berezovskiy Avatar answered Sep 30 '22 18:09

Sergey Berezovskiy