Comment by enlightens
21 hours ago
Ok but var has been around since C# 3.0 in 2007. Love it or hate it, using that keyword in 2025 signals nothing about how current your skills are.
https://en.wikipedia.org/wiki/C_Sharp_3.0#Local_variable_typ...
21 hours ago
Ok but var has been around since C# 3.0 in 2007. Love it or hate it, using that keyword in 2025 signals nothing about how current your skills are.
https://en.wikipedia.org/wiki/C_Sharp_3.0#Local_variable_typ...
You are right about this not being a new feature. But if you don't use it, it seems like you haven't updated your skills in a while.
Besides making the code harder to read, "var" also makes your code less reliable as seen in this example: https://circles.page/567f44465c28b00bf8ed6cf9/Csharp-Type-In...
SomeMethod().Fire(); has the same "problem". var e = new Employee(); does not.
The problem you see is independent from var.
You are right, SomeMethod().Fire() has the problem too. But typically you write
This does NOT have the same problem as var. When you use var you reduce the opportunities for the compiler to catch your bug. So the best practice is to explicitly state the type when possible. It makes the code more readable too.
What's more, Microsoft recommends using implicit typing for local variables only when the type of the variable is obvious from the right side of the assignment. See: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals...
But that's not what the community is doing, and some tools (JetBrains Rider) recommend using var whenever possible.
from your sibling comment: > "var" also makes your code less reliable as seen in this example
I disagree with this too, I think your example is a classic case of preprocessor directives making it difficult to know what your code is doing because the build system is going to conditionally change your code. Var or not, you can't even know what's being compiled just by looking at the file, and that's a larger problem than the use of var
https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...
Use of preprocessor in the example is incidental. The problem with var is that you're not completely stating your intent, leaving it to the compiler to infer your intent. This can lead to trouble in some cases.
I have seen code that sorts numbers as strings, because nowhere in the code was the intent stated that the array is supposed to hold numbers. As a result, if the programmer forgot to convert strings to integers at input time, the bug is never caught.
See: https://circles.page/567f44465c28b00bf8ed6cf9/Csharp-type-in...