5

Consider the following code sample, where Concrete derives from Base:

class Base{} class Concrete : Base {} static void Foo<T>() where T : Base { if (typeof(Concrete).IsAssignableFrom(typeof(T))) { var x = new Bar<T>(); // compile error on this line } } class Bar<T> where T : Concrete { } 

On the line where I am having the compile error, I have already checked that the generic argument is assignable to the Concrete type. So in theory I believe there should be a way to create an instance of the Bar class.

Is there any way I can remove the compile error? I cannot think of a way to cast the argument.


Full text of compile error:

Error 14 The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Bar'. There is no implicit reference conversion from 'T' to 'Concrete'.

8
  • 1
    That compiles for me... is that the actual example? are there perhaps parameters in your real code? Commented Nov 6, 2012 at 14:43
  • 1
    Your code doesn't match the error message. Surely you wrote Bar<T>(); Commented Nov 6, 2012 at 14:44
  • Is there a reason that Foo doesn't have where T : Concrete? Commented Nov 6, 2012 at 14:45
  • while editing, you might also want to clarify the relationship between Base and Concrete Commented Nov 6, 2012 at 14:47
  • 1
    @ZaidMasud thanks; with that edit: there is no regular way to do that. You can hack it with reflection (MakeGenericMethod etc), but that is not a good answer. If you can remove the constraint from Bar<T> and do some casting (via object) inside Bar<T>, that might work. Commented Nov 6, 2012 at 14:58

1 Answer 1

5

The compiler has no way to know that T, which is currently constraint to Base is actually Concrete, and that even if you test it before.

So:

Type type = typeof(Bar<>); Type generic = type.MakeGenericType(typeof(T)); var x = Activator.CreateInstance(generic); 

Don't let it the chance to do it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.