JL.
JL.

Reputation: 81342

C# how to dynamically cast an object?

I am building a helper object that has a property called Mailer. In reality Mailer can be either a System.Net.Mail.MailMessage or a Mono.System.Net.Mail.MailMessage. So I would preferably only want 1 declaration of mailer.

For example I don't want:

private Mono.Mailing.MailMessage MonoMessage = new Mono.Mailing.MailMessage();
private System.Net.Mail.MailMessage MailMessage = new System.Net.Mail.MailMessage();

I would prefer

object mailer;

Then in constructor

switch (software)
            {
                case EnunInternalMailingSoftware.dotnet:
                    this.mailer = new System.Net.Mail.MailMessage();
                    break;
                case EnunInternalMailingSoftware.mono:
                    this.mailer = new Mono.Mailing.MailMessage(); 
                    break;
            }

The problem is that mailer has no properties at design time. So I can't compile my code.

How can this be fixed, am I taking the right approach. Thanks in advance

Upvotes: 0

Views: 334

Answers (1)

Paolo
Paolo

Reputation: 22646

You should use the adapter pattern for this: http://en.wikipedia.org/wiki/Adapter_pattern

Define an interface that covers the methods you need (e.g. SendMail()) and then write a simple adapter class for each MailMessage object that implements the interface and delegates to the correct methods on the specific MailMessage class.

Upvotes: 8

Related Questions