1

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.

Community
  • 1
  • 1
Voo
  • 29,040
  • 11
  • 82
  • 156

4 Answers4

4

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • But is there any reason for that? I mean an assumed C#+ could easily change that rule without breaking anything, seems to me. So is it just a "simpler this way" or are there any corner cases where it would really make a problem? – Voo Apr 03 '12 at 01:47
  • 1
    @Voo: I can't think of any corner cases, but it would probably break `callvirt` (which expects a certain method signature) without extensive modification. So... "simpler this way" I suppose. But for good reason. – Ry- Apr 03 '12 at 01:49
1

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.

Jim Rhodes
  • 5,021
  • 4
  • 25
  • 38
0

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

Attila
  • 28,265
  • 3
  • 46
  • 55
0

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.

weeyoung
  • 172
  • 5
  • 1
    I'm guessing `object` :) And yes, they usually do allow you to override `ToString`. I can't say I've ever seen a class that uses `sealed` on `ToString`, actually. – Ry- Apr 03 '12 at 01:39
  • Well not directly `object` actually, but for simplicity you can assume that just as well ;-) There's no sealed ToString involved anywhere. – Voo Apr 03 '12 at 01:43