Saturday, May 13, 2023

What is method hiding in C#? | Method hiding in c#| method hiding

 What is method hiding in C#?

Method hiding in C# is a technique where a subclass provides a new implementation of a method that is already defined in its superclass, but without using the `override` keyword. Instead, the subclass method is defined with the `new` keyword, which tells the compiler that this is a new method that hides the original method in the superclass.


Here is an example of method hiding in C#:



class Animal

{

    public void MakeSound()

    {

        Console.WriteLine("The animal makes a sound");

    }

}


class Cat : Animal

{

    public new void MakeSound()

    {

        Console.WriteLine("Meow");

    }

}



In this example, we define a class called `Animal` with a method called `MakeSound()`. We then define a subclass called `Cat` that hides the `MakeSound()` method with its own implementation using the `new` keyword.


When we call the `MakeSound()` method on a `Cat` object, the subclass's implementation will be executed:



Animal myAnimal = new Animal();

Cat myCat = new Cat();


myAnimal.MakeSound(); // outputs "The animal makes a sound"

myCat.MakeSound(); // outputs "Meow"

((Animal)myCat).MakeSound(); // outputs "The animal makes a sound"



In this example, calling `MakeSound()` on the `Animal` object will execute the `Animal` class's implementation, while calling `MakeSound()` on the `Cat` object will execute the `Cat` class's implementation, demonstrating method hiding. However, if we cast the `Cat` object to `Animal` and call `MakeSound()`, the `Animal` class's implementation will be executed, since the `new` keyword only hides the method in the subclass, not in the superclass.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...