English
Summary
Conclusions
Inheritance creates a derived class based on a base class and models an “is-a” relationship. A derived class receives the members of the base class, protected members are accessible only to descendants, and constructors are not inherited but are called in a chain through base(…) from the base class to the derived class. Virtual methods overridden with the override modifier provide polymorphism: the call is determined by the object’s actual type, so one piece of code works with different derived classes. Hiding with new selects the method by the variable’s type and is rarely used. All classes derive from object and can override ToString, Equals, and GetHashCode. Types are checked with is, as, and patterns; sealed prohibits inheritance; custom exceptions inherit from Exception; and when there is no “is-a” relationship, composition is used instead of inheritance.
Self-check questions
- What is inheritance? How do you declare a derived class?
- Which base class members are accessible in a derived class? What is the
protectedmodifier for? - In what order do constructors run? What is
base(…)for? - How do the
virtual,override, andnewmodifiers differ? - What are polymorphism and late binding?
- What role does the virtual method table play?
- What methods does the
objectclass have? Which of them are virtual? - What rules must you follow when overriding
EqualsandGetHashCode? - How do upcasting and downcasting differ?
- How do the
isandasoperators differ? What is a type pattern? - When is it better to use virtual methods, and when a
switchon types? - What is the
sealedmodifier for? - How do you create a custom exception class?
- How does composition differ from inheritance? What is the fragile base class problem?
- How are generalization, association, aggregation, and composition shown in UML diagrams?
Useful links
- Inheritance: https://learn.microsoft.com/dotnet/csharp/fundamentals/object-oriented/inheritance
- Polymorphism: https://learn.microsoft.com/dotnet/csharp/fundamentals/object-oriented/polymorphism
overrideandnew: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywordssealed: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/sealed- Custom exceptions: https://learn.microsoft.com/dotnet/standard/exceptions/how-to-create-user-defined-exceptions
- The
Objectclass: https://learn.microsoft.com/dotnet/api/system.object