tags:

views:

51

answers:

1

This may not the worded quite right but here goes anyway.

If I have the following statements;

DocumentMerger<EmailMerge> mailMerge = new DocumentMerger<EmailMerge>();
List<MailMessage> mailMessages = mailMerge.Process();

DocumentMerger<SmsMerge> mailMerge = new DocumentMerger<SmsMerge>();
List<SmsMessage> smsMessages = mailMerge.Process();

How can I create a generic class that takes a type as its generic such as EmailMerge and returns either a list of MailMessage or SmsMessage objects?

I have a class called DocumentMerger which creates my object EmailMerge or SmsMerge.

I now need both of them to expose a Process method which returns its own unique list of objects such as List<MaileMessage> or List<SmsMessage>

I suspect proxies might be the go here but can't work out the code.

Please re-title this question if you think it's not clear enough.

+2  A: 

An interface could solve your problem..

public interface IDocumentMerger
{
}

public interface IOutputType
{
}

public class MailMessage : IOutputType
{
}

public class EmailMerge : IDocumentMerger
{
}

public class SmsMerge : IDocumentMerger
{
}

public class DocumentMerger<T> where T : IDocumentMerger
{
  public List<IOutputType> Process()
  { 
      IOutputType result = null;

      if (typeof(T) == EmailMerge)
      {
          result = new MailMessage();
      }

      // etc..
      // do stuff..

      return result;
  }
}

And you'd use it like this:

var documentMerger = new DocumentMerger<EmailMerge>();

var emailMerge = documentMerger.Process();

emailMerge is of type List<MailMessage>...

I hope I understood your question correctly.. Code is untested, but should be correct.. Or really close to it :)

Ian

edit -- looks like I misread your requirements.. it's an easy fix though, see edit.

Ian P
You can extend this solution to have a Factory Pattern in place, by simply adding another Facotry class. This could avoid a few switch cases and conditions in your calling class. Ref: http://msdn.microsoft.com/en-us/library/ee817667.aspx
Srikanth Venugopalan
I'm not really understanding what IOutputType is because I get a conversion error at result = new MailMessage(); Sorry, but am I missing something here?
griegs
griegs -MailMessage should implement the IOutputType interface.
Ian P