Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics Warning T has same name as type from other type

Tags:

c#

generics

Given the following

public class Service<T> : IService<T>
{
        Repository<T> _repository = new Repository<T>();
        public T Get<T>(int id)
        {
            return _repository.Get<T>(id);
        }
}
public interface IService<T>
{
        T Get<T>(int id);
}

I get the following warning

Type parameter 'T' has the same name as the type parameter from outer type 'Services.IService'

I am not sure what the issue is with this, why does it care if my return type is the same as the type I am telling the class to be. Am I missing something here?

like image 514
jquery auth Avatar asked Sep 10 '10 16:09

jquery auth


2 Answers

You can leave out the <T> in the declaration of Get methods. You are not introducing a new Type Parameter for the Get method which <T> says. The fact that you return a T is enough.

I think this will work:

public class Service<T> : IService<T>
{
    Repository<T> _repository = new Repository<T>();
    public T Get(int id)
    {
        return _repository.Get(id);
    }
}
public interface IService<T>
{
    T Get(int id);
}

You can create a generic method in both generic and non-generic classes.

public class Foo
{
    public T Get<T>(int a)
    {
    }
}

You could also do this in a generic class, but over a different type.

public class Foo<T>
{
    public S Get<S>(int a)
    {
    }
}
like image 124
Jeroen Huinink Avatar answered Nov 19 '22 22:11

Jeroen Huinink


You'd want this instead:

public class Service<T> : IService<T>
{
    Repository<T> _repository = new Repository<T>();
    public T Get(int id)
    {
        return _repository.Get<T>(id);
    }
}

public interface IService<T>
{
    T Get(int id);
}

Basically in you're code you're trying to define Get<T>(). When you put that generic definition, you're saying it's specific to that method, not the whole class.

like image 20
TheCloudlessSky Avatar answered Nov 19 '22 22:11

TheCloudlessSky