Blogs

To var or not to var: Understanding the Usage of the var Keyword in C#

Author: Sunil Shahi

Introduction:

C# is strongly typed language. Yes, I know that is old news, but sometimes it might not be so evident to neophytes developers or converts who come from another dynamically typed language like javascript. The confusion mostly starts because of the keyword “var”. The “var” keyword in C# is very different than its javascript counterpart

What do you mean?  

Well, unlike javascript, when “var” is used for any variable initialization, the compiler comes to you rescue to figure out what type you meant.  Here are a few examples

var x = 0;  
var y = "some random string"; 
var z = new MyClass(); 
var p = string.Empty; 
var q = string.isNullOrEmpty();  

In all the above cases, the compiler looks at the right side of the code to infer the type of variables. the low-level machine code generated when you write var x = 0; is not different at all from when you write int x = 0; Meaning using var isn’t a departure from “strongly typeness” of C#.

Here is what the compiler infers from the above initializations.

int x = 0;  
string y = "some random string"; 
MyClass z = new MyClass(); 
string p = string.Empty; 
bool q = string.isNullOrEmpty();  

Type information is a very powerful tool to write robust code that you can reason. That’s the reason why we have language like Typescript. 

So what’s the point of “var”? 

“var” was introduced in C# 3.0. When this feature was announced the developer community was highly split whether or not this was a good idea. But this is one of the main points that the language designers had in mind: “Reduce Reducing redundancy in code”.  I will give you an example.

MyClassThatHasNameVeryLongAndDifficultToRemember myclass = new MyClassThatHasNameVeryLongAndDifficultToRemember(); 
Dictionary<string, List<MyClass>> myDictionary = new Dictionary<string, List<MyClass>>(); 
//vs 
var myclass = new MyClassThatHasNameVeryLongAndDifficultToRemember(); 
var myDictionary = new Dictionary<string, List<MyClass>>();  

So should i always use “var”? 

To put it mildly NOOOOOOOOOOOOOOOO!!! If you were tired of reading through my rant. THIS IS THE POINT I WANT YOU TO REMEMBER.  If you are asking yourself, “Should I use var here?”. This is the answer. forget about all the lines of code that come before or after the line of code you are considering. Can you easily reason/guess what is the type that var is referring to? if yes use it else not.    

Example.  

 Do this. 


var myClass = new MyClass(); 
var str = string.Empty; 
var x = 0;  

DO NOT do this. 

var stuff = GetMeTheSuffFromSomeMethod();//what are you getting from that method? 
var items = _context.BillingInformation 
                .Include(bi => bi.Client) 
                    .ThenInclude(c => c.Owner) 
                .Select(bi => MapToSomethingThatIsNotEasilyUnderstandable(bi));  

Conclusion:

The “var” keyword in C# serves as a tool to reduce redundancy in code and enhance code readability in appropriate scenarios. It allows the compiler to infer the type based on the initialization, making code more concise. However, it is essential to use “var” judiciously and consider whether it enhances or hinders code readability and maintainability. By choosing the appropriate usage of “var,” developers can strike a balance between conciseness and clarity in their code.