Alex Aparin
Alex Aparin

Reputation: 4512

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?

Upvotes: 2

Views: 87

Answers (2)

Jamiec
Jamiec

Reputation: 136104

It you have an inheritance hierarchy, yet at run time you need to know what concrete class you're dealing with in order to know what to do - chances are you're doing it wrong!

public abstract class A
{
    public abstract void DoSomething();
}

public class B: A
{
    public override void DoSomething() { .. do B's thing ... }
}

public class C : A
{
    public override void DoSomething() { .. do C's thing ... }
}


...
public void Consumer(A a)
{
    a.DoSomething(); // calls the right DoSomething, B or C.
}
...

Note that the above is overly contrived example. There are other things to consider (like, is a public abstract method the right thing to do!)

Upvotes: 5

ViRuSTriNiTy
ViRuSTriNiTy

Reputation: 5155

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)
    }
}

Upvotes: 5

Related Questions