Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic type casting in parameter in c#

Tags:

c#

dynamic

I happen to see a code something like this.

function((dynamic) param1, param2);

When and why do we need this kind of dynamic type casting for parameters?

like image 554
prosseek Avatar asked Oct 12 '11 20:10

prosseek


People also ask

What is dynamic type casting?

The dynamic type cast converts a pointer (or reference) to one class T1 into a pointer (reference) to another class T2 . T1 and T2 must be part of the same hierarchy, the classes must be accessible (via public derivation), and the conversion must not be ambiguous.

Can you cast variables in C?

Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.

What is type casting in C with example?

In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do. For instance, in case we assign a float variable (floating point) with an integer (int) value, the compiler will ultimately convert this int value into the float value.

What is static and dynamic casting in C++?

static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.


1 Answers

It can be used to dynamically choose an overload of function(...) based on the type of param1 at runtime, for example:

public static void Something(string x)
{
    Console.WriteLine("Hello");
}

public static void Something(int x)
{
    Console.WriteLine("Goodbye");
}
public static void Main()
{
    object x = "A String";

    // This will choose string overload of Something() and output "Hello"
    Something((dynamic)x);

    x = 13;

    // This will choose int overload of Something() and output "Goodbye"
    Something((dynamic)x);
}

So even though x is a reference to object, it will decide at runtime what overload of Something() to call. Note that if there is no appropriate overload, an exception will be thrown:

    // ...
    x = 3.14;

    // No overload of Something(double) exists, so this throws at runtime.
    Something((dynamic)x);
like image 151
James Michael Hare Avatar answered Oct 03 '22 03:10

James Michael Hare