Actarius
Actarius

Reputation: 49

Call an overloaded method based on type without checking the type - c#

I have a class called BasePaymentTransactionDataand several classes that inherit from it. I need to map data into an instance of this class I call transaction. The issue is I have to check if the transaction is a specific type and then call the associated overloaded function

This is my code:

class BasePaymentTransactionData { }

class CreditCardPrimaryRequestData : BasePaymentTransactionData { }

class transaction
{
    CreditCardPrimaryRequestData Map(CreditCardPrimaryRequestData transaction)
    {
         return transaction;
    }

    private BasePaymentTransactionData MapTransactionObject(BasePaymentTransactionData transaction, NameValueCollection parameters, string transactionType, string paymentMethod)
    {
        //BasePaymentMapping

        //Specific Mapping
        if (transaction is CreditCardPrimaryRequestData)
            transaction = Map(transaction as CreditCardPrimaryRequestData);

        // many more derived types ...

        return transaction;
    }
}

I was hoping it'd be possible to do something like

transaction = Map(transaction)

And the code would discern it's type and send it to the correct method. Is there any way to do this, or is the above the best I can do?

Also, I know it'd be preferable to just make an interface, and make a virtual Map() method, and just call that, but unfortunately I am unable to do that since I'm working with a lot of code that's framework level and wasn't designed by me

Upvotes: 1

Views: 266

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205589

You can use DLR dynamic dispatch feature:

private BasePaymentTransactionData MapTransactionObject(BasePaymentTransactionData transaction, NameValueCollection parameters, string transactionType, string paymentMethod)
{
    transaction = Map((dynamic)transaction);
    return transaction;
}

But make sure in addition to the specific Map overloads you also have something like this, otherwise you'll get an exception:

BasePaymentTransactionData Map(BasePaymentTransactionData t)
{
    return t;
}

A better type safe way would be to implement double dispatch (Visitor Pattern), but it would require more coding.

Upvotes: 2

Related Questions