Pascal
Pascal

Reputation: 12885

Override generic methods in c#

I thought I can not override generic methods of a derived class.

http://my.safaribooksonline.com/book/programming/csharp/9780071741163/generics/ch18lev1sec13

The code in this link runs fine. The overriden method is called although the instance type of

the base class is used and not the instance of the derived type.

Now I am confused because a former question of mine Type parameter declaration must be identifier not a type

is about calling the overriding generic method with the instance of base type which did NOT work!

Upvotes: 3

Views: 2119

Answers (2)

tmesser
tmesser

Reputation: 7666

The problem is simple confusion over method signatures and declarations. The linked code is overriding a method signature of return T, no parameters with return T, no parameters. This is perfectly fine as the method signatures are the same.

The linked question attempts to override a return of Document<T, U> with Document<type1, type2>, which is invalid in and of itself due to types not being permitted in generic brackets, but also invalid because the override changes the method signature.

Upvotes: 1

luksan
luksan

Reputation: 7777

When you declare a method, you need to use a type parameter. When you invoke a method you use either a type parameter or a type, depending on if you're programming generically.

Valid declaration:

void DoSomething<T>(T input)
{
 ...
}

Invalid declaration:

void DoSomething<int>(T input)
{
 ...
}

Valid invocation:

DoSomething<int>(input);

Valid invocation (if S is a type parameter previously defined in this scope):

DoSomething<S>(input);

Valid invocation (since type parameter T can be inferred from the argument input):

DoSomething(input);

Upvotes: 0

Related Questions