.NET class inherits object class by default. How?

后端 未结 3 1713
猫巷女王i
猫巷女王i 2021-01-22 04:54

When we create a class Product

class Product
{
}

What I have learned from different blogs and books that Object class is the super

相关标签:
3条回答
  • 2021-01-22 05:14

    As per MSDN:

    Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.

    And why do you not 'see' this in the code:

    Languages typically do not require a class to declare inheritance from Object because the inheritance is implicit.

    So in short the .Net type system does this implicit.

    0 讨论(0)
  • 2021-01-22 05:20

    When you want to explore how things happen, you can always take it one step lower and look into the emitted metadata and IL code generated for each method.

    For example, this is a Person class with one property, Name:

    public class Person
    {
        public string Name { get; set; }
    }
    

    When we look at the emitted IL we see (using ILSpy) :

    .class public auto ansi beforefieldinit ConsoleApplication2.Person
        extends [mscorlib]System.Object
    {
       // Property declaration removed for brevity
    }
    

    The compiler add the extends [mscorlib]System.Object, where mscorlib is the declared assembly, System is the namespace and Object is the declared type.

    0 讨论(0)
  • 2021-01-22 05:22

    Yup, it's taken care by .Net Framework. Every Type inf is stored in a special table in memory when program is running. And type record contains link to a base class record. Every type that is not derived from any class contains a link to an object record.

    Through this every type has methods, that are defined in a MethodTable (also in memory when .Net framework is running) as methods of object class. For example GetHashCode or Equals

    0 讨论(0)
提交回复
热议问题