Difference between object a = new Dog() vs Dog a = new Dog()

前端 未结 6 1507
野性不改
野性不改 2020-12-29 04:03
object a = new Dog();

vs

Dog a = new Dog();

In both cases a.GetType() gives Dog. Both

6条回答
  •  甜味超标
    2020-12-29 04:34

    new Dog() is an expression that creates a new Dog instance. It invokes the parameterless constructor of the Dog class.

    a is a variable: a storage cell in memory that holds a reference to the Dog instance after assignment.

    The difference is that a Dog variable can only hold a reference to a Dog instance (or an instance of any class that derives from Dog), while an object variable can hold a reference to an object instance (or an instance of any class that derives from object – which the Dog class does).

    When you have a Dog variable, you can invoke any method defined by the Dog class (and its base classes) on the referenced instance. When you have an object variable, you can only invoke the methods of the object class on the instance.

提交回复
热议问题