The use of ‘var’ in C#

I don’t like to use var because it reduce the readability of code. Look at the below code.

var itemNumber = items.Count();

You can’t confirm the exact data type of itemNumber. It can be int or long or any other integer types. Many people says that IDE like Visual Studio shows you the data type when you hover mouse on it. Yes that is true. But what happen if you are not reading this code on Visual Studio? Many times we read code on GitHub or StackOverflow.

I think it always a good habit to use explicit data types.

int itemNumber = items.Count();

C# language specification says that, only use var when the data type is readable clearly from the right side of the assignment. In other cases use explicit data types.

Now there is a good alternative in C# 9.0 even when you are creating new object.

MyClass mc = new();

It is better than ‘var’.

var mc = new MyClass();

You need to use var in case you are creating an anonymous type.

var filteredPeople = from person in people
                     where person.IsAdult
                     select new 
                     { 
                         Name = $"{person.FirstName} {person.LastName}",
                         person.Address 
                     };

foreach(var filteredPerson in filteredPeople)
{
    Console.WriteLine(filteredPerson.Name);
    Console.WriteLine(filteredPerson.Address);
}

References

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s