I am trying to overload these methods in my visual studio but I face with CS0128 error, what can I do to fix this code?
static int Sum(int x, int y) => x + y;
static double Sum(double x, double y) => x + y;
I am trying to overload these methods in my visual studio but I face with CS0128 error, what can I do to fix this code?
static int Sum(int x, int y) => x + y;
static double Sum(double x, double y) => x + y;
2
Answers
I think it highly likely you’ve made a new project and done this (among other bits of code, but this is the relevant bit):
Without realising (not your fault, it’s not obvious) that when you do that, the compiler helps you out by surrounding your code with a Main method for you. You can’t see it doing this, it just does it:
The problem now is that you’ve got something that falls foul of the compiler rules in C#: you can’t have two local functions (things that look like a method, declared inside the
{ }
brackets of another method, and available only within that enclosing method) with the same name, even if their arguments differ.To fix it, expand your program to be a normal one that doesn’t use top level statements. You can do this easily by pressing Ctrl + . and choosing "Convert to Main style program":
Or you can add the missing class/Main yourself..
Then you can move your local functions out of the Main and into the class scope, where they are allowed to have the same name and different arguments:
The issue occurs due to the fact that you use top-level statements or more specifically how top-level statements are implemented.
The documentation states:
Behind the scenes the compiler (= Roslyn) therefore actually generates a
Program
class with aMain()
method (names might differ, just for illustration here). Also all the methods become local functions in thatMain()
method.To make that clearer that means when you write a program like that:
It’s like you’d be writing it like that:
And here you’ll also get the same error i. e. because local functions in the same scope cannot have the same name.
To prevent this, you just need to make sure that the functions are actually members of the class. However, this also means you cannot use top-level statements.
This works just fine.
FYI: From what I understand from the docs and this Github issue – Scenario 2 top-level statements where implemented that way to be able to support adding top-level functions eventually in the future. So maybe you might be able to do something like this in a similar fashion in the future.