Reputation: 1658
this is something really simple Im sure, but Im struggling to get my head around the inheritance malarky when it comes to interfacing.
Given the following classes, how do I interface the Get method in an interface specific to class Parent, without overriding the base method?
public class Base<T, T2>
{
public T Get<T, T2>(string key)
{
...
}
}
public class Parent : Base<Type1, Type2>, IParent
{
...
}
Here's what I have atm, but I keep getting a "inteface member Type1 IParent.Get(string) is not implemented" error.
public interface IParent
{
Type1 Get(string key);
}
Upvotes: 7
Views: 2320
Reputation: 29244
Try this. You do not override the base Get
and you implement IParent
.
public class Type1 { }
public class Type2 { }
public interface IParent
{
Type1 Get(string key);
}
public class Base<T, T2>
{
public T Get(string key)
{
return default(T);
}
}
public class Parent : Base<Type1, Type2>, IParent
{
}
Upvotes: 1
Reputation: 19203
When matching methods, this signature must match exactly. One of the components of the signature is the number of generic arguments.
Your IParent
interface contains a method Get
with zero type arguments. Your Base
class contains a method Get
with two type arguments.
While it looks like Base.Get
shares its type arguments, it does not, the syntax used creates two new type arguments that shadow the type arguments of the class.
The fix is to simply implement a Get
method in Parent
that does not have any type arguments.
Upvotes: 2
Reputation: 5132
The T Get<T,T2>(string)
method of Base<T,T2>
and the method Type1 Get(string)
method of IParent
are two different method signatures. You would need to implement both. If you wanted both implementations to use the same functionality you could do the following:
public class ParentJ : Base<Type1, Type2>, IParent {
public Type1 Get(string key) {
return this.Get<Type1,Type2>(key);
}
}
However I believe that your original intent is not to parameterize the Get()
method in Base<T,T2>
therefore you would write Base
like so:
public class Base<T,T2> {
public T Get(string key) {
// implementation here
}
}
That signature would satisfy the method signature in IParent
.
You only need type parameters (e.g. T
and T2
) on methods when the type cannot or should not be inferred by the class that contains the method.
Upvotes: 2
Reputation: 11542
public T Get<T, T2>(string key)
will create a generic method on generic class. T
and T2
will be arguments of this generic method and will have no relation to class's T
and T2
.
Just make it public T Get(string key)
.
Upvotes: 5