I have a certain code snippets that needs to be executed if data-type of the variable matches to a certain base-type.Currently I'm doing this using if-else loop
ex:
if(a is float)
{
// do something here
}
else if (a is int)
{
// do something here
}
else if (a is string)
{
// do something here
}
As i have too many types against which i have to compare ,Using If else is quite clumsy . As C# doesn't allow type switching , Is there an alternative way to do this?
Refactor the code and use method overloading:
void SomeCode()
{
...
Action(3.0f); // calls float overload
Action("hello"); // calls string overload
...
}
void Action(float a)
{
...
}
void Action(int a)
{
...
}
void Action(string a)
{
...
}
EDIT:
By using the dynamic
keyword (.NET 4) it works this way (full console app):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SomeCode();
}
static void SomeCode()
{
object o = null;
switch (new Random().Next(0, 3))
{
case 0:
o = 3.0f;
break;
case 1:
o = 3.0d;
break;
case 2:
o = "hello";
break;
}
Action((dynamic)o); // notice dynamic here
}
static void Action(dynamic a)
{
Console.WriteLine("object");
}
static void Action(float a)
{
Console.WriteLine("float");
}
static void Action(int a)
{
Console.WriteLine("int");
}
static void Action(string a)
{
Console.WriteLine("string");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With