To Var or not to Var
One thing I have discovered as a C# developer, is that the ‘var’ keyword can be a subject that divides opinions.
What difference does the ‘var’ keyword make?
Functionally, very little indeed. Unlike the ‘dynamic’ keyword, the ‘var’ keyword is evaluated at compile time, as opposed to run time. The ‘var’ keyword is therefore mainly used to reduce the clutter of explicitly declaring the type. The trouble is, sometimes when the data type can be difficult to implicitly infer for other human readers that are not familiar to the context that it is used in. In cases like these, excessive use of the ‘var’ keyword should be avoided.
In other scenarios, however, it can be quite clear what type is being declared or instantiated and in cases like these the use of the ‘var’ keyword is a lot less problematic. One example of this scenario is when a new instance of an object is created using the ‘new’ keyword where the name of the type is explicitly show on the right-hand side of the declaration.
What about performance?
Since the ‘var’ keyword is evaluated at compile-time and not run-time, its use doesn’t raise any performance concerns.
Is the use of this keyword always a subjective issue?
No. With some research I have discovered that there are scenarios where the use of the ‘var’ keyword is a necessity. One example of this is when Linq is used along with anonymous types that are being projected using a ‘select’ in the query statement.
Conclusion
In my opinion, the use of this keyword is appropriate in circumstances where the data type is clear or where the use of ‘var’ is needed. It comes down to experience and good judgement in the end.
Long time C# user, since C#1. I am avid use of var as it removes lots of noise when working with generics. Some generic signatures can quickly get really ugly.
I know some prefer to be more explicit but as long as the code is well written removing the type noise can help improve clarity imho
Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
https://abieerasmus.wordpress.com/