If you have a set of polymorphic functions
that do different things dependent up on the data type and you have stored your
data as an object, how do you call the correct method for the object?
An example of this might be if you have a data set that you bind to a grid and
want to output something to the clipboard dependent upon the data type.The
common way to do this might be to do a series of if statements that compare
Types.
e.g
if(obj.GetType()
== typeof(int)){
MethodCall((int)obj);
}
If you define a number of methods that overload the parameters and start with an
object, then the compiler will not allow you to not specify the type that you
have. To get over this define an overload that has object as the parameter. It
now compiles but the newly added object overload is the only method that is ever
called.
But, there is a way to do this polymorphically with the use of the dynamic
keyword. This allows us to pass a value as dynamic and have its type defined at
runtime. At runtime the value can then be used to select the correct method to
call.
By first calling a jump-off method where the parameter is dynamic it allows the
runtime to decide what the type is, from there you call out to the Polymorphic
method and the correct type is selected.
It is always useful to have an overload that takes object as the parameter in
order for any cases that you dont have a handling method for. If no method is
found that will take a parameter of the type passed then a runtime exception is
thrown.
class
Program
{
static void Main(string[]
args)
{
object value = 10.0d;
DynamicCall(value);
}
public static
void DynamicCall(dynamic initialValue)
{
Call(initialValue);
}
public static
void Call(double value)
{
Console.WriteLine("Double
Value");
}
public static
void Call(bool value)
{
Console.WriteLine("Boolean
Value");
}
public static
void Call(int value)
{
Console.Write("Int
Value");
}
public static
void Call(object value)
{
Console.WriteLine("Object
Value");
}
}