tags:

views:

42

answers:

1

I've asked this question before but I don't think I explained myself clearly so I'm going to try again.

I have the below code;

public interface IDocumentMerger
{
    List<???????> Process();
}

public class EmailMerger : IDocumentMerger
{
    public void Process()
    {
        return new List<MailMessage>();
    }

}

public class DocumentMerger<T> where T : IDocumentMerger
{
    public T objMerger;

    public DocumentMerger()
    {
        Type t = typeof(T);
        objMerger = (T)Activator.CreateInstance(t);
    }

    public List<???????> Process()
    {
        return objMerger.Process();
    }

}

I want to use the above something like this;

DocumentMerger<EmailMerger> merger = new DocumentMerger<EmailMerger>();
List<MailMessage> messages = merger.Process();

DocumentMerger<SmsMerger> merger = new DocumentMerger<SmsMerger>();
List<SmsMessage> messages = merger.Process();

But I can't figure out how to return either a list of type MailMessage or a list of type SmsMessage depending on whether I create a DocumentMerger passing int either MailMerger or SmsMerger.

+4  A: 

Your interface needs to be generic:

public interface IDocumentMerger<DOCTYPE>
{
  List<DOCTYPE> Process(); 
} 

Then your classes need to implement the generic interface:

public class EmailMerger : IDocumentMerger<MailMessage>
public class SMSMerger : IDocumentMerger<SmsMessage>

I'm not sure why you have a DocumentMerger class as well but that would be like this:

public class DocumentMerger<MERGERTYPE, DOCTYPE> where MERGERTYPE : IDocumentMerger<DOCTYPE>

And then your methods need to return the appropriate types:

// In EmailMerger
public List<MailMessage> Process()  

// In SMSMerger
public List<SmsMessage> Process()  

// In DocumentMerger
public List<DOCTYPE> Process()

Why don't you just make EmailMerger/SMSMerger instances though, as DocumentMerger is just wrapping one of these at a time (using reflection no less)?

Graphain
I wanted to create a type of factory so that you called a single object and just changed the type and hence the returned type. the goal was to make it easy for others to call
griegs
How is making a new factory per type easier than creating a type?
Graphain