C# how to dynamically cast an object?

Posted by JL on Stack Overflow See other posts from Stack Overflow or by JL
Published on 2010-05-25T09:33:35Z Indexed on 2010/05/25 9:41 UTC
Read the original article Hit count: 247

Filed under:

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

© Stack Overflow or respective owner

Related posts about c#