6

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.

2 Answers 2

7

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) 
    { 
        ...
    } 
} 
Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.