Search code examples
c#genericstypesgeneric-type-argument

C# generic type : Warning from outer type


I have a controller called UserController with generic type T:

public class UserController<T> : Controller
{    
}

And then, inside this class I have a method called Select() with generic typing:

public override T Select<T>(ushort id)
{
    // UserModel is just a Class where I is an integer typed property
    UserModel.I = 2;
    object result = UserModel.I;

    return (T)Convert.ChangeType(result, typeof(T));
    throw new NotImplementedException();
}

Now in another form class I am accessing this method like this:

// This is so far working
UserController<int> us = new UserController<int>(0);
label1.Text = us.Select<string>(0);

Now I am having this warning:

Severity    Code    Description Project File    Line    Suppression State
Warning CS0693  Type parameter 'T' has the same name as the type 
parameter from outer type 'UserController<T>'

I am not understanding what it is saying here:

Type parameter 'T' has the same name as the type 
parameter from outer type 'UserController<T>'

What am I doing wrong here?


Solution

  • If you want your method to be parameterized with the same type as your class, then you don't include a generic parameter in the method name:

    public override T Select(ushort id) /* Uses T from class */
    

    However, from your other sample it looks like you want to use different types - so use a different name for the parameter:

    public override TInner Select<TInner>(ushort id)
    {
        // UserModel is just a Class where I is an integer typed property
        UserModel.I = 2;
        object result = UserModel.I;
    
        return (TInner)Convert.ChangeType(result, typeof(TInner));
    
    
        throw new NotImplementedException();
    }
    

    (In general, try to pick better names than just T or even TInner - just as you should pick good names for other parameters, try to convey the purpose of the type in the type parameter name)