I have a doubt, i’ve searched a lot about it and i haven’t found nothing that can explain.
I can have a property referencing an interface inside my class, and make use of DI to fill these property. For example:
public interface ITest {
void DoSomething();
}
public class Test {
ITest _test;
public Test(Itest _test)
{
this._test = test;
}
}
The problem is, if I have an generic interface, and my class don’t make use of generics, when i create these property a compile error is raised
public interface ITest<T> {
void DoSomething(T parameter);
}
public class Test {
ITest<T> _test; //error (Type cant be found)
public Test(Itest<T> _test)
{
this._test = test;
}
}
Is this possible?
Your
Testclass needs to be generic too – otherwise there’s no way of knowing what kind ofITest<T>the_testvariable refers to. How would you know how to call_test.DoSomething()? The type parameter ofTestdoesn’t have to beT, of course:You’d then construct it as:
Type safety would stop you from writing:
because you can’t construct a
Test<int>from anITest<string>.Alternatively, your
Testclass may only need to take one specific kind ofITest, and therefore not be generic at all:It all depends on what you’re trying to achieve.
EDIT: As noted in comments, if your
Testclass doesn’t use any of the aspects ofITest<T>which rely onT, you might want to create a non-generic base interface:Then you could make your class just depend on the non-generic
ITestinterface instead ofITest<T>.