I hope the question is correct, so let’s give you an example. Imagine the following generic 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 the MSDN the keyword where restricts the type parameter T to be of type Base or to inherit from this class.
[…] a where clause can include a base class constraint, which states that a type must have the specified class as a base class (or be that class itself) in order to be used as a type argument for that generic type.
Also this code does compile:
public static T GetFirst()
where T : Base
{
// Call GetList explicitly using Base as type parameter.
return (T)GetList<Base>().First();
}
So when following the last code typeof(T) should return Base, shouldn’t it? Why does Visual Studio then prints this warning to me?
warning CS0184: The given expression is never of the provided (‘Demo.Base’) type.
typeof(whatever)always returns an instance of typeType.Typedoesn’t derive fromBase.What you want is this:
Something that looks like it is the same is this:
But that has a different meaning.
The first statement (with
typeof(Base)) only istrueifTisBase. It will befalsefor any type derived fromBase.The second statement (
variableOfTypeT is Base) is alwaystruein your class, because any class derived fromBasewill returntruefor a check for its base class.