Reputation: 837
I want to set local variable BarService<T1> service;
as described on class Foo
.
Code is as follows:
class Foo
{
// error i got here and want to use this instead of using dynamic
BarService<T> service;
//dynamic service
internal void SetBarService<T>() where T : class, new()
{
service = new BarService<T>();
}
internal IEnumerable<T2> GetAll<T2>() where T2 :class
{
return service.GetAll<T2>();
}
}
public class BarService<T> where T : class
{
internal IEnumerable<T> GetAll<T>()
{
throw new NotImplementedException();
}
}
Can anyone clear the error for me?
Upvotes: 0
Views: 190
Reputation: 70701
If you want to use an open generic type as the type of your field, then you have to make the whole class generic, not just the method:
class Foo<T> where T : class, new()
{
BarService<T> service;
internal void SetBarService()
{
service = new BarService<T>();
}
internal IEnumerable<T2> GetAll<T2>() where T2 :class
{
return service.GetAll<T2>();
}
}
It is unclear what the relationship between GetAll<T2>()
and the rest of the code is, but with luck the above would work.
Of course, whether you can actually make your class Foo
into a generic class depends on how it's used elsewhere in the code. There's not enough context in your question to know if there are going to be other problems. But the above is the basic idea.
Upvotes: 2