views:

87

answers:

2

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.

+5  A: 

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) 
    { 
        ...
    } 
} 
Jordão
cool that works thanks.
ealgestorm
+1  A: 

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!

Tomas Petricek