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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jaganathan BantheswaranPosted Oct 24, 2013, 7:47 AM
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].
Shankar MPosted Oct 24, 2013, 7:30 AM
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 BantheswaranPosted Oct 21, 2013, 4:07 AM
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!");
}
}
}