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

前端 未结 6 1518
野性不改
野性不改 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:30

    Both statements contain a declaration and a constructor invocation. The invocations of the constructor are identical, therefore you get a Dog in both cases. The declarations are different: in the first case, you declare a variable of type object, a superclass of Dog; in the second case, you declare a variable of type Dog. The difference is that in the subsequent code you can invoke methods of Dog without a cast only when you declare the variable as Dog; if you declare it as object, you would need a cast.

提交回复
热议问题