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

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

    Both create a Dog object. Only the second allows you to directly invoke Dog methods or to otherwise treat it like a dog, such as if you need to pass the object to a method as a parameter of type Dog (or something in the Dog hierarchy that is more specific than simply object).

    object obj = new Dog(); 
    // can only see members declared on object
    var type = obj.GetType(); // can do this
    Console.WriteLine(obj.ToString()); // also this
    obj.Bark(); // Error! Bark is not a member of System.Object
    
    Dog dog = new Dog();
    // can do all of the methods declared for Object
    dog.Bark(); // can finally use the method defined for Dog
    

提交回复
热议问题