Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between method hiding and shadowing in C#?

What is the difference between method hiding and shadowing in C#? Are they same or different? Can we call them as polymorphism (compile time or run time)?

like image 733
Shailesh Jaiswal Avatar asked Nov 28 '22 22:11

Shailesh Jaiswal


2 Answers

What is the difference between method hiding and shadowing in C#?

Shadowing is another commonly used term for hiding. The C# specification only uses "hiding" but either is acceptable.

You call out just "method hiding" but there are forms of hiding other than method hiding. For example:

namespace N
{   
    class D {}
    class C 
    {
        class N
        {
            class D
            {
                 N.D nd; // Which N.D does this refer to?

the nested class N hides the namespace N when inside D.

Can we call them as polymorphism (compile time or run time)?

Method hiding can be used for polymorphism, yes. You can even mix method hiding with method overriding; it is legal to introduce a new virtual method by hiding an old virtual method; in that case which virtual method is chosen depends on the compile-time and run-time type of the receiver. Doing that is very confusing and you should avoid it if possible.

like image 50
Eric Lippert Avatar answered Dec 10 '22 13:12

Eric Lippert


The VB.NET compiler calls it shadowing, in C# it is called hiding. Calling it shadowing in C# is a spill-over from VB.

And it is a a compiler warning, it essentially is a name-conflict between base and derived class.

Can we call them as polymorphism (compile time or run time)?

It certainly is not a form of runtime polymorphism. A call to a hiding or to a hidden method is resolved at compile time. Which makes that it will in general not be called or considered polymorphism.

like image 36
Henk Holterman Avatar answered Dec 10 '22 13:12

Henk Holterman