Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type parameter declaration must be an identifier not a type

Tags:

c#

generics

There is a base class which has one method of generic type and I am sure that in my derived I will be returning 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 doesn't compile. Can anybody spot the mistake? I am sure that in my Extended class I want to return string only. How do I solve this?

like image 776
Jaggu Avatar asked Sep 06 '11 04:09

Jaggu


Video Answer


1 Answers

You cannot override a generic method with a concrete implementation; that's not how generics work. The Extended class must be able to handle calls to GetSomething<int>() for example.

In other words, the signature for an overriding method must be identical to the method it is overriding. By specifying a concrete generic 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 the JIT should optimize away the conditional when compiling a particular instantiation of this method. (If it doesn't then it's not a very good JIT!)

(The syntax for your override is technically correct, but fails for other reasons as well. For example, you can't use the keyword string as a generic parameter name. And if you could, your code still wouldn't do what you want, nor would it compile, since the compiler would be unable to find a method with that signature on a supertype.)

like image 95
cdhowie Avatar answered Oct 20 '22 12:10

cdhowie