Error compiling non-standard generics

I have two classes: base class and 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 will 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 when overriding the child 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?

+5
source share
2 answers

It works. You should have made 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>();
}

Here are some basic C # override rules:

The overridden base method must have the same signature as the overriding Method.

This means the same type of return value and the same method arguments.

+3
source

, . - , , .

+2

All Articles