开发者

using var has any side effects? [duplicate]

This question already has answers here: Closed 11 years ago. 开发者_StackOverflow

Possible Duplicate:

C# 'var' vs specific type performance

Are there any performance costs (in terms of type conversion, etc.) if I write the line

SqlConnection c = new SqlConnection(connectionString))

as

var c = new SqlConnection(connectionString))


No. The compiled IL is identical.

The only potential side effect is in the case of inheritance, if you're variable definition is a base class, and you instantiate a subclass. If you do:

 BaseClass item = new DerivedClass();

This will potentially act differently than:

 var item = new DerivedClass();

This is because the second compiles to:

 DerivedClass item = new DerivedClass();

In most cases, it should behave identically (due to the Liskov substitution principle). However, if DerivedClass uses method hiding it is possible to have a change in behavior.


No. The compiler knows at compile time what var should be (the return of new SqlConnection is, in fact, SqlConnection. When the compiler knows the type of the right hand side, you can use var.

This has no runtime performance implications


I believe var is processed at compile time, so it is simply a shortcut for writing the code. This means that the compiled version is identical.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜