C# Question

Should I use dynamic keyword to optimize conversions?

I have simple hierarchy of classes (base class A, derived class B : A, derived class C : A, etc). I have following code:

void computation(A base_class)
{
if (base_class is B)
{
//Do some stuff with (base_class as B)
}
if (base_class is C)
{
//Do some stuff with (base_class as C)
}
}


I remembered about dynamic keyword of c# language. As I understood, I can use following code (to optimize extra conversions).

void computation(A base_class)
{
dynamic temp = base_class as B;
if (temp != null)
{
//Do some stuff with temp
}
temp = base_class as C;
if (temp != null)
{
//Do some stuff with (base_class as C)
}
}


Which variant is better for usage? What about performance of these approaches?

Answer

This smells like premature optimization and i dont like the dynamic usage here.

Also keep in mind that dynamic does specific things like (quote from MSDN):

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time.

So i guess bypassing compile time type checking is not what you want.

I recommend using var instead. Imho it improves readability, debugging is easier and using as instead of is + casting is also a bit faster.

void computation(A base_class)
{
    var b = base_class as B;
    if (b != null)
    {
        //Do some stuff with temp
    }
    var c = base_class as C;
    if (c != null)
    {
        //Do some stuff with (base_class as C)
    }
}
Comments