Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

c# - 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.

question from:https://stackoverflow.com/questions/3658407/use-of-var-type-in-variable-declaration

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...