Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "var" to declare variables in C#

Tags:

c#

.net

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?

like image 913
Developer Avatar asked Dec 31 '08 16:12

Developer


People also ask

How do you declare a variable in C?

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.

What does VAR do in C?

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.

Does VAR exist in C?

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.

Is it better to use VAR or type C#?

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.


2 Answers

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.

like image 102
configurator Avatar answered Oct 20 '22 16:10

configurator


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>>();
like image 28
joshperry Avatar answered Oct 20 '22 15:10

joshperry