Reputation: 29658
I know from this question that var i = 1
and int i = 1
are exactly the same in IL. The compiler simply replaces var
with the actual type at compile time. But, are there any instances where var
could cause problem behavior (maybe the compiler guesses the wrong type?)
Upvotes: 3
Views: 168
Reputation: 29823
var x = 0
x = 0.10
Cannot convert source type 'double' to target type 'int'
An example:
double x = 0; //to initialize it
switch (something) {
case condition1:
x = 0.1;
break;
case condition2:
x = 0.2;
break;
}
Using var
instead of double
will give a compiler error.
Upvotes: 0
Reputation: 126834
I don't believe the compiler will guess the wrong type. However, it might infer a type you didn't intend, but that's not the same.
Consider the perfectly legal
decimal foo = 10;
decimal bar = 4;
decimal baz = foo / bar;
In the code, baz
will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different.
var foo = 10;
var bar = 4;
var baz = foo / bar;
Now everything infers to int and baz
is 2 because now the math is taking place with integers.
So, yes, code semantics could theoretically change if you introduce var
where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be
var foo = 10m;
Upvotes: 8
Reputation: 77520
In addition to the ambiguous:
var x = null;
the compiler will also not infer the type of overloaded method groups:
var m = String.Equals;
nor will it infer the type of lambda expressions, which can be either Func<>
or Expression<Func<>>
:
var l = (int x) => x + 1;
All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over var
in VS to see the static type.
Upvotes: 1
Reputation: 12854
It won't cause any "issues", regarding code however you could have a regression issue...
IObject1
{
void DoSomething();
}
IObject2
{
void DoSomething();
}
var result = SomeMethod();
result.DoSomething();
Now, if SomeMethod returned IObject1 and then was changed to return IObject2 this would still compile. However, if you expect DoSomething to execute particular code then this could potentially be a regression issue.
However, if you have
IObject1 result = SomeMethod();
If the return type of SomeMethod is changed you'll know it right away.
Upvotes: 2
Reputation: 4951
No, I don't think so. The only time it can't figure things out is if you try to do something like
var product = null;
Which makes sense, and in this case you get a compile error.
Upvotes: 2