---
title: "What is the purpose of polymorphism in C# and how is it implemented?"  
description: "What is the purpose of polymorphism in C# and how is it implemented?"  
author: "Utpal Vishwas"  
published: 2023-07-02  
updated: 2023-07-04  
canonical: https://www.mindstick.com/forum/158921/what-is-the-purpose-of-polymorphism-in-c-sharp-and-how-is-it-implemented  
category: "oops"  
tags: ["c#", "oops"]  
reading_time: 2 minutes  

---

# What is the purpose of polymorphism in C# and how is it implemented?

What is the [purpose](https://yourviews.mindstick.com/view/247/no-fail-policy-failing-its-purpose) of [polymorphism in C#](https://answers.mindstick.com/qa/82404/what-is-polymorphism-in-c-sharp) and how is it implemented?

## Replies

### Reply by Aryan Kumar

In C#, [polymorphism](https://www.mindstick.com/articles/1827/objective-c-polymorphism) is the ability to use a variable of one type to refer to an object of another type. This is possible because C# supports inheritance, which allows classes to inherit from other classes.

Polymorphism is implemented in C# using the `is` and `as` keywords. The `is` keyword can be used to check if a variable is of a particular type. The `as` keyword can be used to cast a variable to a different type.

For example, the following code defines a class `Animal` and a derived class `Dog`:

C#

```plaintext
class Animal
{
}

class Dog : Animal
{
}
```

The following code creates a variable of type `Animal` and assigns it to an object of type `Dog`:

C#

```plaintext
Animal animal = new Dog();
```

The `animal` variable is now of type `Animal`, but it is also pointing to an object of type `Dog`. This is because `Dog` inherits from `Animal`.

The following code uses the `is` keyword to check if the `animal` variable is of type `Dog`:

C#

```plaintext
bool isDog = animal is Dog;
```

The `isDog` variable will be `true` because the `animal` variable is pointing to an object of type `Dog`.

The following code uses the `as` keyword to cast the `animal` variable to a type `Dog`:

C#

```plaintext
Dog dog = animal as Dog;
```

If the `animal` variable is actually of type `Dog`, the `dog` variable will be assigned the value of the `animal` variable. Otherwise, the `dog` variable will be `null`.

Polymorphism is a powerful feature that can be used to make code more flexible and reusable. It can be used to create generic code that can work with objects of different types.


---

Original Source: https://www.mindstick.com/forum/158921/what-is-the-purpose-of-polymorphism-in-c-sharp-and-how-is-it-implemented

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
