tags:

views:

119

answers:

2

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?

+2  A: 

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.

Igor Zevaka
can you edit 1 more time? the classes need indenting to format properly AFAICT
James Manning
Oops, corrected.
Igor Zevaka
+2  A: 

Your override cannot change the return type, even if the return type derives from the base class method's return type. You have to do something like what Igor did above, and make the return type generic.

John Saunders