none
why does the var in this problem not cause a compilation error RRS feed

  • Question

  • Hi,

    Please consider the following code. In this code, we have used var d = new B(); The variable d can be of

    type B or A. Yet the code compiles. why?

    public class A { } public class B:A { } public class C:B { } class TestComplex { static int Main(string[] args) { A a1 = new A(); B b1 = new B(); C c1 = new C(); var d = new B(); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); return (0); } }

    regds

    Manoj Gokhale


    Sunday, December 23, 2012 4:55 PM

Answers

  • I am not sure what you are asking.  var means to figure out what type the variable is from what the variable is being assigned.

    so the compiler sees your code like this.

    B d = new B();

    Sunday, December 23, 2012 4:58 PM
  • Hi!

    The code "new B()" is returning a new instance of B. This is something the compiler knows so the variable d is of Type B.

    The compiler is not interested in the fact, that an instance of type B could also be stored in a reference to A or a reference to Object. It always takes the strongest type. (Else var couldn't be used at all, because all classes derive from object - either directly or indirectly.)

    With kind regards,

    Konrad

    Sunday, December 23, 2012 6:37 PM
  • While it is true that any instance of B may be cast to an A, variable d is an instance of a B because of the New.  In other words, to get an "A" type from d, you must cast the object to an A, which will work.

    --
    Mike
    Sunday, December 23, 2012 6:42 PM

All replies

  • I am not sure what you are asking.  var means to figure out what type the variable is from what the variable is being assigned.

    so the compiler sees your code like this.

    B d = new B();

    Sunday, December 23, 2012 4:58 PM
  • Hi!

    The code "new B()" is returning a new instance of B. This is something the compiler knows so the variable d is of Type B.

    The compiler is not interested in the fact, that an instance of type B could also be stored in a reference to A or a reference to Object. It always takes the strongest type. (Else var couldn't be used at all, because all classes derive from object - either directly or indirectly.)

    With kind regards,

    Konrad

    Sunday, December 23, 2012 6:37 PM
  • While it is true that any instance of B may be cast to an A, variable d is an instance of a B because of the New.  In other words, to get an "A" type from d, you must cast the object to an A, which will work.

    --
    Mike
    Sunday, December 23, 2012 6:42 PM