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?
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)
{
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With