Type cast to generic type


The following question got posted to one of the internal DLs.

Why does the following fail to compile.

public interface A { }
public class B : A { }
public class C : B { }

class D
public void f()
C c = new B() as C; // Valid!

public void g<T>() where T : A
T t = new B() as T; // Invalid! Error CS0413

The constraint (where T : A) clearly tells the compiler that T is A and B derives from A. So it should've been possible to cast B into T. However, the compiler fails with a "The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint".

If the above was possible then I would've been able to do the following

struct S1 : A { }
D d = new D();
d.g<S1>(); // meets the constraint that S1:A

This means that effective we are doing  T t = new B() as S1. But the C# spec clearly calls out "In an operation of the form e as T, e must be an expression and T must be a reference type". This means that using a struct (value type) in an as statement is not allowed and would make the above illegal.

The solution is to tell the compiler that I'd only send reference types for T and you do this by

public void g<T>() where T : class, A
T t = new B() as T; // Invalid! Error CS0413

Comments (6)

  1. Mihailik says:

    Well, if you unconditionally cast B to T, you would better add stronger constraint ‘where T : B’.

    It might be the case that you do the cast in some if/else branch. In that case you could have used brackets-cast operation:

    T t = (T)((IA)new B());

    There is no need for addition constraint if the logic doesn’t imply that requirement.

  2. Would this work?

    public void g<T>() where T : B


       T t = new C() as T;


  3. Mihailik says:

    It would, for obvious reason: T still may be a struct, and ‘as’ operation is not allowed for structs.

  4. Mihailik says:

    Sorry, I meant ‘it would NOT’.

  5. kkris1983 says:

    It will work like this:

    T t = (T)(object)new B();

  6. carpediem says:

    dejaron de tener utilidad los cast al aparecer la genericidad restringida?

Skip to main content