Concept of Downcasting in C#

Mannan Ul Haq
0
Downcasting is the process of converting a variable from a base class type to a derived class type. This is necessary when you have a reference to a base class object, but you need to call a method or access a property that only exists in the derived class.

Consider the following class hierarchy:

class Animal
{
    public void Eat()
    {
        Console.WriteLine("The animal eats");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("The dog barks");
    }
}

Now, let's say you have a reference to an `Animal`:

Animal myAnimal = new Dog();

`myAnimal` is actually a `Dog`, but because its compile-time type is `Animal`, you can only call `Animal` methods on it. If you want to call `Dog`-specific methods, like `Bark()`, you need to downcast it to a `Dog`:

Dog myDog = myAnimal as Dog;
if (myDog != null)
{
    myDog.Bark();  // Outputs: "The dog barks"
}

The `as` keyword is used for safe casting. It returns `null` if the cast fails, rather than throwing an `InvalidCastException`.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !