Comment by recursive
17 hours ago
SomeMethod().Fire(); has the same "problem". var e = new Employee(); does not.
The problem you see is independent from var.
17 hours ago
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.
Microsoft recommendation is reasonable. I don't think var should be used as much Rider recommends. But var is perfectly fine in itself. The problem you illustrated occurs independently from var. You assert that one "typically" writes code a certain way but I've seen plenty of both. Further, sometimes you need var. Sometimes the target type can't be spelled like with anonymous types.
You are contradicting yourself... var is perfectly fine... but it shouldn't be used as much...
1 reply →