← Back to context

Comment by breadwinner

11 hours ago

You are right, SomeMethod().Fire() has the problem too. But typically you write

   Employee e = SomeMethod();
   e.Fire();

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...

    • Sorry for being unclear. Var is perfectly fine in many cases. Sometimes there are better tools. Screwdrivers are fine tools but they are not appropriate for driving nails.