Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird generics compile error

Tags:

c#

.net

generics

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?

like image 524
Jouke van der Maas Avatar asked Jun 06 '10 19:06

Jouke van der Maas


1 Answers

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.

like image 147
Igor Zevaka Avatar answered Sep 26 '22 15:09

Igor Zevaka