Why does VS warn me that typeof (T) is never a provided type in a generic method, where the type parameter is limited to implement T?

Hope this question is correct, so give you an example. Imagine the following general method:

public abstract class Base : IDisposable { public static IEnumerable<T> GetList<T>() where T : Base { // To ensure T inherits from Base. if (typeof(T) is Base) throw new NotSupportedException(); // ... } } 

According to MSDN , the where keyword restricts a parameter of type T Base or inherits from this class.

[...] the where clause may include a base class constraint, which states that the type must have the specified class as the base class (or be that class itself) in order to be used as a type argument for this generic type.

Also this code compiles:

 public static T GetFirst() where T : Base { // Call GetList explicitly using Base as type parameter. return (T)GetList<Base>().First(); } 

So, when Base should be returned after the last typeof(T) code, right? Why does Visual Studio then print this warning for me?

warning CS0184: this expression never refers to the provided type (Demo.Base).

+8
generics c # visual-studio type-parameter
source share
2 answers

typeof(whatever) always returns an instance of type Type . Type not inferred from Base .

What you want is:

 if(typeof(T) == typeof(Base)) throw new NotSupportedException("Please specify a type derived from Base"); 

Something similar to the same:

 if(variableOfTypeT is Base) 

But this has a different meaning.
The first statement (with typeof(Base) ) is only true if T is Base . It will be false for any type derived from Base .
The second statement ( variableOfTypeT is Base ) is always true in your class, because any class derived from Base will return true to test its base class.

+13
source share

This is not how you test inheritance.

typeof(T) is of type System.Type , it is not Base . To find out if T is obtained from Base, you should use the IsSubclassOf method, for example:

 if(typeof(T).IsSubclassOf(typeof(Base)) ... 
+1
source share

All Articles