Click here to Skip to main content
15,886,919 members
Articles / Programming Languages / C#

C# Using Var: To Var or Not To Var?

Rate me:
Please Sign up or sign in to vote.
4.64/5 (4 votes)
12 Dec 2023CPOL2 min read 6.6K   5   7
The article discusses the debate over using C#'s var keyword versus explicit typed variables, highlighting potential issues with overuse of 'var' that can lead to code misunderstandings, readability challenges, and bugs.

Image 1

C# var vs. explicitly typed

This can be one of those developer holy wars to avoid, but here is an opinion on this one.

Using var seems to be the rage today for reducing redundancy. Mostly, var is pretty benign or helpful, but perhaps it shouldn’t be used all the time, as there are possible problems that it could cause, even adding confusion or code misunderstandings in some cases, making code harder to read, or causing bugs.

One possible example of a problem scenario for using var (there could be more)

The only problem is var could hide the type in the code so that you don’t know what is returned, and the actions on the code could not work as expected.

Let’s Say You Wrote Your Own Type Comparison

C#
int Compare(int,int);//compares ints

int Compare(string,string);//does comparison of strings in alphabetical order

return 0 if equal, -1 if parameter 1 is less than parameter 2, 1 if parameter 2 is greater than parameter 1.

Let’s say GetValue originally looked like this:

C#
int GetValue(string);

You wrote code like:

C#
var myvalue1=GetValue("## 10 ##");  //GetValue parses out 10

var myvalue2=GetValue("## 100 ##"); //GetValue parses out 100

if (Compare(myvalue1,myvalue2)>0)

//do something.

In this case, if GetValue was modified either purposely or accidentally to return strings, the comparison would not compare correctly in all cases, but if int was returned from what was parsed, then it would compare correctly. 

If the code had instead been written as below using int instead of var, compilation would have failed if GetValue return value was changed to string:

C#
int myvalue1=GetValue("## 10 ##"); //GetValue parses out 10

int myvalue2=GetValue("## 100 ##"); //GetValue parses out 100

You could say this isn’t something that would happen, but something very similar to this did happen with production code (it was VBScript, which had dynamic typing; in the above scenario, var acts somewhat like that, but instead allowing compilation to happen for something you might not have intended).

Summary

I think it is safer to only use var when the types are obvious (or a few other scenarios that make sense).

Microsoft’s guidelines for var: (“C# Coding Conventions”—Microsoft Learn, n.d.)

Use var when it’s easy to tell the type of the variable being assigned.

You shouldn’t use var when it’s not easy to determine the type visually.

(Microsoft Reference: https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions).

My Recommendations for Guidelines for Var Usage

  • Use var for anonymous types.
  • Use var with linq.
  • As Microsoft says, you can use var if the type is obvious. I say obvious means WITHOUT using IntelliSense (GitHub doesn’t have IntelliSense when reviewing code), with the caveat of if it makes things simpler; but if not, it shouldn’t be a requirement.
  • You “can” use var if the types are crazy complicated and muddle the code (though that is probably a smell itself and ideally avoided).
  • Use explicit types otherwise.

Reference Articles

Some Other Viewpoints on Using Var:

Microsoft Coding Guidelines:

https://msdn.microsoft.com/en-us/library/ff926074.aspx

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Languages/frameworks: C#, .NET, ASP.NET, C/C++, WPF
Experienced in Web development, UI development, frameworks and multi-threading.


Author of the book Essential Software Development Career + Technical Guide.
https://www.amazon.com/dp/B0BXHYWMDP/

Check out our website at:
https://essentialsoftwaredevelopment.com/

Comments and Discussions

 
QuestionI use "var" only temporary Pin
Ralf Peine 202314-Dec-23 5:25
Ralf Peine 202314-Dec-23 5:25 
AnswerRe: I use "var" only temporary Pin
DavesApps14-Dec-23 6:45
DavesApps14-Dec-23 6:45 
QuestionThe Problem Isn't Var Pin
cteague313-Dec-23 9:02
cteague313-Dec-23 9:02 
AnswerRe: The Problem Isn't Var Pin
DavesApps13-Dec-23 9:19
DavesApps13-Dec-23 9:19 
AnswerRe: The Problem Isn't Var Pin
Oleg Shilo25-Dec-23 23:57
Oleg Shilo25-Dec-23 23:57 
Questionvar is strongly typed Pin
MSBassSinger13-Dec-23 6:42
professionalMSBassSinger13-Dec-23 6:42 
AnswerRe: var is strongly typed Pin
DavesApps13-Dec-23 7:13
DavesApps13-Dec-23 7:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.