Voo
Voo

Reputation: 30216

default parameters and overriding

I am wondering why the following is marked as an error with no suitable method found to override in VS2010 (.NET 4):

public override string ToString(int foo=0) {
     // some stuff
}

I've found this which seems somewhat similar (at least also surprising behavior with optional parameters), but I don't understand why this method does not override ToString().

Now I'm obviously aware how to easily fix this problem by overloading ToString, so I'm not interested in solutions for the problem, but in the rationale behind this limitation.

Upvotes: 1

Views: 531

Answers (4)

Jim Rhodes
Jim Rhodes

Reputation: 5085

ToString() and ToString(int) are not the same. If you omit the argument for ToString(int foo=0) it is the same is if you wrote ToString(0). foo is an argument with a default value, not an optional argument.

Upvotes: 1

Ry-
Ry-

Reputation: 224932

It simply doesn't have the same signature. Overriding methods are limited to strictly the same signature as the method that they are overriding, and optional parameters aren't just syntactic sugar for overloading; they're also part of the method signature and even part of the resultant IL code.

This:

public virtual string ToString();

Is not the same as this:

public override string ToString(int foo = 0);

No matter how you slice it. So, error.

Upvotes: 4

weeyoung
weeyoung

Reputation: 172

What class are you inheriting from? It seems from the error 'no suitable method found to override' that the base class does not have a virtual ToString method. Most default c# classes do not allow ToString to be overridden.

Upvotes: 0

Attila
Attila

Reputation: 28762

The function string ToString(int foo=0) has one parameter (even if it does not appear in the code when called), the one you thought of overriding has 0

Upvotes: 0

Related Questions