Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of "var" type in variable declaration

Our internal audit suggests us to use explicit variable type declaration instead of using the keyword var. They argue that using of var "may lead to unexpected results in some cases".

I am not aware of any difference between explicit type declaration and using of var once the code is compiled to MSIL.

The auditor is a respected professional so I cannot simply refuse such a suggestion.

like image 344
Petr Kozelek Avatar asked Sep 07 '10 11:09

Petr Kozelek


People also ask

What type of variable is var?

var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.

Why do we use VAR?

By using “var”, you are giving full control of how a variable will be defined to someone else. You are depending on the C# compiler to determine the datatype of your local variable – not you. You are depending on the code inside the compiler – someone else's code outside of your code to determine your data type.

What does variable is declared as VAR mean?

This means that any variable that is declared with var outside a function block is available for use in the whole window. var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.

Is it necessary to use var keyword while declaring variable?

Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared.


1 Answers

How about this...

double GetTheNumber() {     // get the important number from somewhere } 

And then elsewhere...

var theNumber = GetTheNumber(); DoSomethingImportant(theNumber / 5); 

And then, at some point in the future, somebody notices that GetTheNumber only ever returns whole numbers so refactors it to return int rather than double.

Bang! No compiler errors and you start seeing unexpected results, because what was previously floating-point arithmetic has now become integer arithmetic without anybody noticing.

Having said that, this sort of thing should be caught by your unit tests etc, but it's still a potential gotcha.

like image 171
LukeH Avatar answered Oct 16 '22 07:10

LukeH