How C# compiler interpret objects that specified by var keyword? When do we must use this keyword?
If you mean the "var" keyword used in variable declaration then there is no such thing as "var type". This "var" is interpreted (at compile time) as type inferred from expression that is assigned to the variable.
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.
There are times when you need to use var, for example, when using an anonymous type, such as in a LINQ query:
var results = context.People.Select(p => new {p.PersonID, p.Name});
See the new{} line in there? That's returning a class which is being generated at compile-time. Since this class has no name, the only way you can refer to it in your code is by using "var". This cuts down on you having to create tons and tons of special-purpose classes just for LINQ resultsets.
Under the hood, whether you use var just as a shorthand for another type, or if using an anonymous type, you are still doing static, compile-time type checking. Dynamic types are not being used. The compiler literally figures out what the type should be when you compile, so a program like:
var i = 12;
i = i + "foo!";
won't compile.
In Var declaration,
Compiler infer the type from the assigned value
on
var a = 100; // compiler assumes a is a integer
var b = "test"; // compiler assumes b is a string
Why do we need them (why cant we use objects directly)
Because object doesnt enforce type safety
object objtest = 1;
objtest = "test";
this works fine.
But var enforces type safety
var a = 100;
a= "test";
this doesnt compile, and will give the compile time error.
Where we can use them
- Linq queries returning Anonymous types
- And anywhere you want to define type safe variables (simplicity) . instead of writing something like this.
.
RootClass rt = new RootClass ();
List<RootClass > rt = new List<RootClass >();
you can write like this
var aaaaaa = new RootClass ();
var ls = new List<RootClass>();
Cheers