Lander Verhack | No Overloads with Top-Level Statements
source link: https://blogs.u2u.be/lander/post/2022/02/02/no-overloads-with-top-level-statements
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
No Overloads with Top-Level Statements
These days, you don't need a Program
class with a static void Main()
anymore. You can just write code directly in Program.cs
.
This is called using top-level statements. However, you might run into a couple of surprises when writing code here.
For example, try writing the following functions in Program.cs
:
Program.cs
void Print(int value) => Console.WriteLine(value);
void Print(string value) => Console.WriteLine(value);
This will give you the following exception:
A local variable named 'Print' is already defined in this scope
It seems that overloading is not allowed wile using top-level statements. But why is that?
Investigation
What you need to realize, is that top-level statements are just syntactic sugar. There is still a Program
class with a Main()
method.
You can see this by inspecting your compiled code with something like ildasm
.
What you are writing in Program.cs
is in fact the content of the Main()
method.
That means the Print functions are local functions. They are defined within the declaration space of a function, not of a type (class, struct, ...). Currently overloading is only allowed within the declaration space of a type.
It is possible that one day overloading with local functions will be allowed, but not today.
The (Somewhat of a) Solution
If you really want to define multiple local functions with the same name, you can just use a local scope. This isn't very practical though because the call to the function needs to be in the same scope.
Program.cs
{
Print(7);
void Print(int value) => Console.WriteLine(value);
}
{
Print("Seven");
void Print(string value) => Console.WriteLine(value);
}
Conclusion
Today it's not possible to use overloading in Program.cs
. This might change in the future. However, does it really matter?
You are effectively working with local functions; you can't access them from outside Program.cs
. And if this is just a local effect, how bad is it to just name your functions PrintInt
and PrintString
?
Be the first to rate this post
- Currently .0/5 Stars.
Related posts
- No Overloads with Top-Level Statements
Program.cs void Print(int value) => Console.WriteLine(value); void Print(string value) => Co...
- Where React Fails
Some people like dogs, some people like cats. Some people like React, some people like Angular.
W...
- Reflection With Closures and Performance
In this blog we are going to dynamically create a delegate using reflection both paying attention to...
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK