Is there any technical reason to use or not to use var in C# when the type is known?

后端 未结 8 2103
南方客
南方客 2021-01-02 04:05

It seems that more and more C# code I read uses the var type identifier:

foreach (var itemChange in ItemChanges)
{
   //... 
}
8条回答
  •  难免孤独
    2021-01-02 04:29

    The only technical reason I know of is that you can perform implicit casts without var, e.g.

    int i = 5;
    double a = i; // implicit cast with explicit types
    

    but here I much prefer var as it makes the cast explicit; while I don't care so much about the types I do care when I'm performing a representation changing type conversion:

    var a = (double)i; // explicit cast with implicit types
    

    But really the general reason is readability, as you said. The question you need to ask yourself is why you think the exact concrete type is important for readability? Do you always write Linq queries calling out the concrete type, e.g.

    from ItemChange itemChange in ItemChanges
    
    // instead of
    
    from itemChange in ItemChanges
    

    Similarly, do you always call out the type arguments to generic methods instead of using type inference, e.g.

    ItemChanges.Select((ItemChange itemChange) => ...);
    
    // instead of
    
    ItemChanges.Select(itemChange => ...);
    

    Or are you happy to let the compiler do some work for you and let it work out the types, at the 'expense' of not having the type information explicitly stated?

    If you're happy with type inference in linq and generic methods, then you've already made the decision that you're OK with not having types explicitly spelled out everywhere, and you probably haven't found your code to be any less readable as a result (in fact, you've probably found quite the opposite). So using var is just another step down the same path that you're already on.

提交回复
热议问题