I have two classes, a base class and a child class. In the base class i define a generic virtual method:
protected virtual ReturnType Create<T>() where T : ReturnType {}
Then in my child class i try to do this:
protected override ReturnTypeChild Create<T>() // ReturnTypeChild inherits ReturnType { return base.Create<T> as ReturnTypeChild; }
Visual studio gives this weird error:
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Create()'. There is no boxing conversion or type parameter conversion from 'T' to 'ReturnType'.
Repeating the where clause on the child's override also gives an error:
Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly
So what am i doing wrong here?
This works. You had to make the return type generic:
public class BaseClass {
public virtual T Create<T>() where T : BaseClass, new() {
var newClass = new T();
//initialize newClass by setting properties etc
return newClass;
}
}
public class DerivedClass : BaseClass {
public override T Create<T>() {
var newClass = base.Create<T>();
//initialize newClass with DerivedClass specific stuff
return newClass;
}
}
void Test() {
DerivedClass d = new DerivedClass() ;
d.Create<DerivedClass>();
}
These are some basic C# override rules:
The overridden base method must have the same signature as the override method.
This means the same return type and same method arguments.
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