Using members of Var type

93 views Asked by At

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?

2

There are 2 answers

1
Jon Skeet On

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
0
bytecode77 On

If you use var, the you have to immediately initialize the variable. Example:

var a = 1;

This tells the compiler it's an int. But if you don't initialize, then the compiler doesn't know what type it should be using.

var b;

What type is b?

The same applies for members of classes.

var is just a convenience feature so you don't have to type in the name of the class or the fully qualified namespace.