Generic methods and warning CS0184: The given expression is never of the provided '%typename%') type

In the given example...


public virtual type GetUser< type>() where type: class
{
  if( typeof( type) is User)
  {
    // do something
  }

  string temp = typeof(type).FullName;

  if( temp.CompareTo( "User") == 0)
  {
    return _myUser as type;
  }
  throw new NotSupportedException( "Type is not supported");
}

 



Why does the C# compiler generate the following warning:


warning CS0184: The given expression is never of the provided 'GenericsDemo.User') type
 


at this expression:


if( typeof( type) is User)
 



Thanks,
Neno



Answer this question

Generic methods and warning CS0184: The given expression is never of the provided '%typename%') type

  • Miljac

    Because typeof(x) will return a System.Type object.  A System.Type object won't every be your custom User class type.  Change the line to

    if (type is User)

    and then you will be asking the compiler to determine if 'type' is derived from User.

    Michael Taylor - 10/13/05

  • thomsson

    Ah, sorry.  Didn't notice that you were using a generic parameter.  I thought it was a parameter name.  Since you have the type you should use the following code:

    typeof(CustomClass).IsAssignableFrom(typeof(T))

    This says that if you can assign to an instance of CustomClass another object of type T (the generic parameter) then do something.  This should only be true if T is either of type CustomClass or if it derives from CustomClass.  Note that this only works for classes.  Any other type (such as value types or interfaces) will always return false.  If you are dealing with interfaces then you'll need to use

    typeof(T).GetInterface("<interface>")

    If it returns null then the type doesn't implement the interface.

    Michael Taylor - 10/17/05

  • krinpit

    Thanks, looks likes an easy one. However after I made the change the compiler generated the following error:



    error CS0118: 'type' is a 'type parameter' but is used like a 'variable'
     


    Thanks,
    Neno



  • Generic methods and warning CS0184: The given expression is never of the provided '%typename%') type