Hi Experts,
While reading I have come across that we can refactor Switch statement with OOP Paradigm Ploymorphism. I got some links but quite confusing.
Can you explain them with a simple example.
Any help appreciated.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jaganathan BantheswaranRank #170 · 14.1K reputationPosted Oct 21, 2013, 12:07 AM EDT
If you are designing an application with OOPs C# & you are using Switch Statement, we can replace the switch statement with polymorphism concept.
Here is working example
using System.IO;
using System;
class Program
{
static void Main()
{
Animal[] ani = new Animal[] { new Dog(), new Cat() };
// Using Switch
foreach (Animal a in ani)
{
a.makeSound();
var type = a.GetType();
switch (type.ToString()) {
case "Dog":
a.makeSound();
break;
case "Cat":
a.makeSound();
break;
}
}
//Eliminating Switch
foreach(Animal animal in ani)
{
animal.makeSound();
}
}
abstract class Animal {
public abstract void makeSound();
}
class Dog : Animal {
public override void makeSound() {
Console.WriteLine("Woof!");
}
}
class Cat : Animal {
public override void makeSound() {
Console.WriteLine("Meow!");
}
}
}
Shankar MRank #874 · 2.5K reputationPosted Oct 24, 2013, 3:30 AM EDT
Thanks for your prompt reply. Can you Please explain how this can be achieved. how can use Polymorphism in this case to elimimate using Switch statement
For Ex:
foreach (DataRow dr in dt.Rows)
{
switch(dr["value"].ToString())
{
case a :
MethodA();
break;
case a :
MethodB();
break;
case a :
MethodC();
break;
}
}
Thanks, Shankar M
Jaganathan BantheswaranRank #170 · 14.1K reputationPosted Oct 24, 2013, 3:47 AM EDT
We can eliminate the switch case by using Polymorphism only where your are following OOP design but NOT in normal Switch usage like you example.
If you want to use polymorphism, then your methods class structure should be as my example[Should follow OOP].