I know that the title may be confusing (or even misleading), but I’m planning to create an interface which is generic, and it should implement a method involving a generic parameter.
When implemented in class AFirst, it should have a method MyMethod<A>() that returns the type A, and when implemented in class BFirst, it should have a method MyMethod<B>() that returns type B. I need this functionality as there is an inheritance relationship between A and B (and MANY others) and I need a generic method that I can call with any of the base classes.
If it was confusing, have a look at what I want to do:
Consider B derives from A.
Consider AFirst and BFirst implement IMyInterface<A> and IMyInterface<B> respectively:
BFirst mySecondObj = new BFirst();
A myA = BFirst.MyMethod<A>();
B myB = BFirst.MyMethod<B>();
I need access to the MyMethod templates for the base classes to, so when I instantiate the BFirst instance, I can call either MyMethod for A or B. I’m building a template system and think these AFirst and BFirst are the templates, and MyMethod acts like a factory method. I will have a big hierarchy, and the project needs to be extensible by deriving even more classes from my base class A, so I can’t just create seperate interfaces or methods for each of them.
I tried this:
interface IMyInterface<T> where T : A
{
T GetNewInstance<T>();
}
and I tried to implement this way, but I’m getting it as created like this when I click implement:
class AFirst : IMyInterface<A>
{
public T GetNewInstance<T>()
{
throw new NotImplementedException();
}
}
Didn’t make sense to me in the way that I’ve specified the T type to be A, but it still implements as T. For example, it will go like this (below is how I want it to happen)
class AFirst : IMyInterface<A>
{
public A GetNewInstance<A>()
{
throw new NotImplementedException();
}
}
class BFirst : AFirst, IMyInterface<B>
{
public B GetNewInstance<B>()
{
throw new NotImplementedException();
}
}
and from outer code, call the sample as in the beginning of my question:
BFirst myBFirst = new BFirst();
A a = BFirst.GetNewInstance<A>(); //calls AFirst's method and returns A
B b = BFirst.GetNewInstance<B>(); //calls BFirst's method and returns B
How is this possible?
Thanks,
Can.
In your generic interface you define a generic method. I think that’s where the confusion is. It should be a normal method that returns your generic type. I.e.
This will get implemented as
which I’m guessing is what you want.