In C#, how does keyword var
work?
The best thing I can do is using var , but the var keyword doesn't exist in C.
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).
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.
var is used to declare the variable in javascript.
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:
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.
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.
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