-3

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?

bytecode77
  • 14,163
  • 30
  • 110
  • 141
salil87
  • 111
  • 1
  • 5
    What happens when you try? – David Jun 07 '15 at 11:36
  • 1
    Aside: you don't declare an *object* using `var`; you declare a *variable*. It's a good idea to keep a very clear separation in your head between variables, objects, references etc. – Jon Skeet Jun 07 '15 at 11:39

2 Answers2

6

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
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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.

bytecode77
  • 14,163
  • 30
  • 110
  • 141