jess jess - 3 months ago 28
C# Question

Overriding inherited generic methods

I have this code in base class

protected virtual bool HasAnyStuff<TObject>(TObject obj) where TObject:class
{
return false;
}


In child class I am overriding

protected override bool HasAnyStuff<Customer>(Customer obj)
{
//some stuff
if Customer.sth etc
return false;
}


I am getting this error


'''Type parameter declaration must be an identifier not a type'''


What is it I am doing wrong here?

Answer

You can't override a generic method's type parameter in a derived class. To achieve a similar functionality, one option is to have your base class be a generic class, and have your derived class such as

class Derived : BaseClass<Customer>
{
     protected override bool HasAnyStuff(Customer customer)
     {
         // ...
     }
}

where BaseClass is declared as

class BaseClass<T> where T : class
{
    // ...
    protected virtual bool HasAnyStuff(T obj)
    {
         // ...
    }
}

Alternatively, depending on exactly how your derived class is being used, you can just override the HasAnyStuff method with a non-generic Customer argument.

public bool HasAnyStuff(Customer customer)
{
    // ...
}

However, note that the new HasAnyStuff will not be called if you are not working with an instance of DerivedClass. That is to say,

BaseClass foo = new DerivedClass();
foo.HasAnyStuff(new Customer());

will call BaseClass's generic method, not DerivedClass's non-generic method.