Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "var" mean in C#? [duplicate]

Tags:

c#

In C#, how does keyword var work?

like image 249
alansiqueira27 Avatar asked Nov 29 '10 19:11

alansiqueira27


People also ask

Is there VAR in C?

The best thing I can do is using var , but the var keyword doesn't exist in C.

What does VAR mean in programming?

Definition and Usage The var statement declares a variable. Variables are containers for storing information. Creating a variable in JavaScript is called "declaring" a variable: var carName; After the declaration, the variable is empty (it has no value).

What is the purpose of using VAR?

By using “var”, you are giving full control of how a variable will be defined to someone else. You are depending on the C# compiler to determine the datatype of your local variable – not you. You are depending on the code inside the compiler – someone else's code outside of your code to determine your data type.

Does var stand for variable?

var is used to declare the variable in javascript.


2 Answers

It means that the type of the local being declared will be inferred by the compiler based upon its first assignment:

// This statement: var foo = "bar"; // Is equivalent to this statement: string foo = "bar"; 

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar"; foo = 1; // Compiler error, the foo variable holds strings, not ints 

var has only two uses:

  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };

You cannot use var as the type of anything but locals. So you cannot use the keyword var to declare field/property/parameter/return types.

like image 65
cdhowie Avatar answered Oct 02 '22 13:10

cdhowie


It means the data type is derived (implied) from the context.

From http://msdn.microsoft.com/en-us/library/bb383973.aspx

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed int i = 10; //explicitly typed 

var is useful for eliminating keyboard typing and visual noise, e.g.,

MyReallyReallyLongClassName x = new MyReallyReallyLongClassName(); 

becomes

var x = new MyReallyReallyLongClassName(); 

but can be overused to the point where readability is sacrificed.

like image 20
D'Arcy Rittich Avatar answered Oct 02 '22 12:10

D'Arcy Rittich