This article explains the main differences among overriding, hiding and shadowing in C#. I am mainly focusing on the main points and not detailed descriptions. So you will finish this very quickly. Also some examples to understand the concepts better are provided.
- The "override" modifier extends the base class method, and the "new" modifier hides it.
- The "virtual" keyword modifies a method, property, indexer, or event declared in the base class and allows it to be overridden in the derived class.
- The "override" keyword extends or modifies a virtual/abstract method, property, indexer, or event of the base class into the derived class.
- The "new" keyword is used to hide a method, property, indexer, or event of the base class into the derived class.
- If a method is not overriding the derived method then it is hiding it. A hiding method must be declared using the new keyword.
- Shadowing is another commonly used term for hiding. The C# specification only uses "hiding" but either is acceptable. Shadowing is a VB concept.
What are the differences between method hiding and overriding in C#?
- For hiding the base class method from derived class simply declare the derived class method with the new keyword.
Whereas in C#, for overriding the base class method in a derived class, you need to declare the base class method as virtual and the derived class method as overriden.
- If a method is simply hidden then the implementation to call is based on the compile-time type of the argument "this".
Whereas if a method is overridden then the implementation to be called is based on the run-time type of the argument "this".
- New is reference-type specific, overriding is object-type specific.
What are the differences between method hiding and method shadowing?
- Shadowing is a VB concept. In C#, this concept is called hiding.
- The two terms mean the same in C#.
Method hiding == shadowing
- In short, name "hiding" in C# (new modifier) is called shadowing in VB.NET (keyword Shadows).
- In C# parlance, when you say "hiding" you're usually talking about inheritance, where a more derived method "hides" a base-class method from the normal inherited method call chain.
- When you say "shadow" you're usually talking about scope; an identifier in an inner scope is "shadowing" an identifier at a higher scope.
- In other languages, what is called "hiding" in C# is sometimes called "shadowing" as well.
Examples 1: Simple one
Output:
Example 2: Method hiding with warning
Output:
Example 3: Overriding, Hiding and Shadowing
Output:
Example 4 : Method Overriding and Method Hiding:
Output:
Please provide your feedback so that I can improve my loop holes.