Search code examples
c#genericsinterface

Implementing interfaces using generics


I'm new to generics and need some help.

I want to create an interface for all "transformer" classes to implement. To be a "transformer" the class must contain at least one variation of T mapTo<T>(T t).

HERE IS HOW I WANT TO USE TRANSFORMERS:
Overload some methods...GREAT! Seems easy enough!

public class Transformer : ITransformer
{
    public Transformer(IPerson instance)
    {
    }

    public XmlDocument mapTo(XmlDocument xmlDocument)
    {
        // Transformation code would go here...
        // For Example:
        // element.InnerXml = instance.Name;

        return xmlDocument;
    }

    public UIPerson maptTo(UIPerson person)
    {
        // Transformation code would go here...
        // For Example:
        // person.Name = instance.Name;

        return person;
    }
}

LET'S USE GENERICS TO DEFINE THE INTERFACE:
Greate idea!

public interface ITransformer
{
     T MapTo<T>(T t); 
}

THE PROBLEM:
If I use generics in the interface my concrete class is LITERALLY forced to implement the following:

public T MapTo<T>(T t)
{
    throw new NotImplementedException();
}

THIS MAKES THE CLASS LOOK RATHER UGLY

public class Transformer : ITransformer
{
    public Transformer(IPerson  instance)
    {
    }

    public XmlDocument MapTo(XmlDocument xmlDocument)
    {
        // Transformation code would go here...
        // For Example:
        // element.InnerXml = instance.Name;

        return xmlDocument;
    }

    public UIPerson MapTo(UIPerson person)
    {
        // Transformation code would go here...
        // For Example:
        // person.Name = instance.Name;

        return person;
    }

    public T MapTo<T>(T t)
    {
        throw new NotImplementedException();
    }
}

Solution

  • Maybe add generic parameter to interface definition:

    public interface ITransformer<T>
    {
         T MapTo(T t); 
    }
    

    And implement all mappings you need:

    public class Transformer : ITransformer<XmlDocument>, ITransformer<UIPerson>