Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#.NET Generic Methods and Inheritance

Is it possible to do the following with generics in C#.NET

public abstract class A
{
    public abstract T MethodB<T>(string s);
}

public class C: A
{
    public override DateTime MethodB(string s)
    {
    }
}

i.e. have a generic method in a base class and then use a specific type for that method in a sub class.

like image 544
eaglestorm Avatar asked May 20 '10 02:05

eaglestorm


2 Answers

The type parameter should be declared with the type, and the subclass will declare the specific type in its inheritance declaration:

public abstract class A<T>
{ 
    public abstract T MethodB(string s); 
} 

public class C: A<DateTime> 
{ 
    public override DateTime MethodB(string s) 
    { 
        ...
    } 
} 
like image 64
Jordão Avatar answered Sep 20 '22 11:09

Jordão


No.

The reason is that you would be providing implementation only for one special case. The base class requires you to implement a MethodB that can work for any type T. If you implement it only for DateTime and if someone calls, for example, ((A)obj).MethodB<int> then you don't have any implementation that could be used!

like image 44
Tomas Petricek Avatar answered Sep 21 '22 11:09

Tomas Petricek