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?
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.
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.
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.
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.
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);
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