Differences Among Method Overriding, Method Hiding (New Keyword) And Method Shadowing In C#

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.

  1. The "override" modifier extends the base class method, and the "new" modifier hides it.
  2. 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.
  3. The "override" keyword extends or modifies a virtual/abstract method, property, indexer, or event of the base class into the derived class.
  4. The "new" keyword is used to hide a method, property, indexer, or event of the base class into the derived class.
  5. If a method is not overriding the derived method then it is hiding it. A hiding method must be declared using the new keyword.
  6. 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#?

  1. 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.
  2. 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".
  3. New is reference-type specific, overriding is object-type specific.

What are the differences between method hiding and method shadowing?

  1. Shadowing is a VB concept. In C#, this concept is called hiding.
  2. The two terms mean the same in C#.
    Method hiding == shadowing
  3. In short, name "hiding" in C# (new modifier) is called shadowing in VB.NET (keyword Shadows).
  4. 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.
  5. When you say "shadow" you're usually talking about scope; an identifier in an inner scope is "shadowing" an identifier at a higher scope.
  6. In other languages, what is called "hiding" in C# is sometimes called "shadowing" as well.

Examples 1: Simple one




Example 2: Method hiding with warning




Example 3: Overriding, Hiding and Shadowing




Example 4 : Method Overriding and Method Hiding

Method Overriding-Method Hiding.jpg


Output-Method Overriding-Method Hiding

Please provide your feedback so that I can improve my loopholes.

Similar Articles