After declaring an object of implicit type with var
keyword, is it possible to use the members, methods or properties specific to the type that has been assigned to it by compiler in any further statements?
Yes, absolute - because var
isn't actually a type. It just tells the compiler: "I'm not going to explicitly tell you the type - just use the compile-time type of the right-hand operand of the assignment operator to work out what type the variable is."
So for example:
var text = "this is a string";
Console.WriteLine(text.Length); // Uses string.Length property
As well as being convenient, var
was introduced to enable anonymous types, where you couldn't declare the variable type explicitly. For example:
// The type involved has no name that we can refer to, so we *have* to use var.
var item = new { Name = "Jon", Hobby = "Stack Overflow" };
Console.WriteLine(item.Name); // This is still resolved at compile-time.
Compare this with dynamic
, where the compiler basically defers any use of members until execution-time, to bind them based on the execution-time type:
dynamic foo = "this is a string";
Console.WriteLine(foo.Length); // Resolves to string.Length at execution time
foo = new int[10]; // This wouldn't be valid with var; an int[] isn't a string
Console.WriteLine(foo.Length); // Resolves to int[].Length at execution time
foo.ThisWillGoBang(); // Compiles, but will throw an exception
See more on this question at Stackoverflow