Skip to content

Clarify method hiding explanation in polymorphism documentation #47378

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/csharp/fundamentals/object-oriented/polymorphism.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,14 @@ If you want your derived class to have a member with the same name as a member i

:::code language="csharp" source="./snippets/inheritance/Inheritance.cs" ID="SnippetNewMethods":::

Hidden base class members may be accessed from client code by casting the instance of the derived class to an instance of the base class. For example:
When you use the `new` keyword, you're creating a method that *hides* the base class method rather than *overriding* it. This is different from virtual methods. With method hiding, the method that gets called depends on the compile-time type of the variable, not the run-time type of the object.

Hidden base class members can be accessed from client code by casting the instance of the derived class to an instance of the base class. For example:

:::code language="csharp" source="./snippets/inheritance/Inheritance.cs" ID="SnippetUseNewMethods":::

In this example, both variables refer to the same object instance, but the method that gets called depends on the variable's declared type: `DerivedClass.DoWork()` when accessed through the `DerivedClass` variable, and `BaseClass.DoWork()` when accessed through the `BaseClass` variable.

### Prevent derived classes from overriding virtual members

Virtual members remain virtual, regardless of how many classes have been declared between the virtual member and the class that originally declared it. If class `A` declares a virtual member, and class `B` derives from `A`, and class `C` derives from `B`, class `C` inherits the virtual member, and may override it, regardless of whether class `B` declared an override for that member. The following code provides an example:
Expand Down