When using "var" to declare variables in C#, is there boxing/unboxing taking place?
Also is there a chance of a runtime type mis-match when using var to declare variables?
Declaring (Creating) Variablestype variableName = value; Where type is one of C types (such as int ), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign a value to the variable.
var data type was introduced in C# 3.0. var is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration.
No. var is a dynamic data type, usually used in JavaScript. C uses static data type, which means you have to initialize the specific data type for each variables. C's data types are int, float, double and char.
var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.
No. using var is compiled exactly as if you specified the exact type name. e.g.
var x = 5;
and
int x = 5;
are compiled to the same IL code.
var is just a convenience keyword that tells the compiler to figure out what the type is and replace "var" with that type.
It is most useful when used with technologies like LINQ where the return type of a query is sometimes difficult to determine.
It is also useful (saves some typing) when using nested generic declarations or other long declarations:
var dic = new Dictionary<string, Dictionary<int, string>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With