A type parameter declaration must be an identifier, not a type

There is a base class that has one method of a general type, and I'm sure that in my derivative I will return a string. This is my code:

public abstract class Base { public virtual T GetSomething<T>() { return default(T); } } public class Extended : Base { public override string GetSomething<string>() { return string.Empty; //return base.GetSomething<T>(); } } 

But this code does not compile. Can anyone spot a mistake? I am sure that in my extended class I only want to return a string. How to solve this?

+8
generics c #
source share
1 answer

You cannot override a general method with a specific implementation; this is not how generics work. The Extended class should be able to handle GetSomething<int>() calls, for example.

In other words, the signature for the overriding method must be identical to the method that it overrides. By specifying a specific general implementation of the method, you change its signature.

Consider using this approach:

 public override T GetSomething<T>() { if (typeof(T) == typeof(string)) return string.Empty; return base.GetSomething<T>(); } 

Note that JIT should optimize the condition when compiling a specific instance of this method. (If this is not the case, then this is not a very good JIT!)

(The syntax of your redefinition is technically correct, but not suitable for other reasons. For example, you cannot use the string keyword as the name of a general parameter. And if you could, t do what you want and not compile, because the compiler cannot find method with this signature in supertype.)

+8
source share

All Articles