How does class inheritance work in C#?

Asked

Viewed 179 times

1

I have class 1 and class 2, class 2 inherits from class 1.

Other classes that inherit from class 2 will inherit the attributes of class 1?

  • 5

    Yes.

  • Thank you : @LINQ

  • But imagine there an interface and a class on the road. Both at 80 per hour. You think you’re on each other’s side?

1 answer

3


Inheritance is a mechanism for reusing code, whether algorithms or data structures. Well roughly the inheritance makes a copy of the class it inherited and sticks to this new one, so everything in class 1 will be in class 2, so if you create class 3 inheriting class 2, everything in class 2 will be in class 3, including what has already been copied class 1.

Of course, the mechanism is a little more complex than that, it’s not a de facto copy, and there are member protection mechanisms, so private members of class 2 or 1 will not be accessible by class 3, and a member protected in class 1 must remain at least protected in class 2 for class 3 to see it. Members are there, they just can’t be accessed in the derivative code.

There is still the issue of virtualization, so class 3 can only override what is allowed by class 2, no matter how it is in class 1, although class 2 cannot give more access than it has itself.

Get the guy Object. It is inherited by all types of C#, directly, even if implicitly, or indirectly because the new guy inherited from a guy he’d already inherited from Object. So Equals(Object), GetHashCode(), GetType() and ToString() will be available in all types written in . NET (ok, there are exceptions, but it escapes from the normal typing of . NET and C#).

Note that there are static members in it. These members obviously do not participate in the inheritance, so they are out. Protected members can be accessed by the derivative type, but are not available for access outside of it, so they are not completely public, they will not be part of the derivative type public contract, but they are there. The same goes for private members that are not even documented, are present in the object, but can not access them normally.

So it’s a hierarchy where members of the ascending type will always be present in their descendants.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.