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?
A method in a generic class can be overridden like any other method. The output is shown here: The overridden version of getValue() is called for objects of type MyClass2, but the superclass version is called for objects of type MyClass.
Similar to John Carpenter's answer, you can override the generic method with the same generic method, but simply use the as operator to check and cast it to the desired type. This has the added benefit of using null-testing to check if the conversion worked.
A generic method may be overloaded like any other method. A class can provide two or more generic methods that specify the same method name but different method parameters.
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
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.
Similar to John Carpenter's answer, you can override the generic method with the same generic method, but simply use the as
operator to check and cast it to the desired type. This has the added benefit of using null-testing to check if the conversion worked.
Base Class
protected virtual bool HasAnyStuff<TObject>(TObject obj) { .... // base implementation }
Inherited Class
protected override bool HasAnyStuff<TObject>(TObject obj) { var customer = obj as Customer; if (customer == null) // conversion failed. object is not of type Customer { return base.HasAnyStuff(obj); } .... // do stuff with the customer }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With