Bartosz
Bartosz

Reputation: 4766

Generic extension method for various types having the same properties

I am wondering, is it possible to create an extension method that will work with a set of different types provided they have the same property? For example:

public static T GetObjectByIdOrName<T>(this IEnumerable<T> collection, Mapping mapping) where T : IType1, IType2, IType3
    {
        return collection.FirstOrDefault(x => x.Id == mapping.ObjectId || x.Name == mapping.ObjectName);
    }

All Types have the Id and Name properties so I hoped this would be possible - however, the compiler is telling me that there is an ambiguous reference between Type1.Id and Type2 Id...

Is there any way to implement this? (I cannot create a common base for them)

Upvotes: 0

Views: 303

Answers (1)

Colin
Colin

Reputation: 4135

It's fairly easy given proper code design. Just have them share a common interface.

public interface IBase
{
    object Id{ get; set; }
    string Name{ get; set; }
}

public interface IType1 : IBase{}
public interface IType2 : IBase{}

public static T GetObjectByIdOrName<T>(this IEnumerable<T> collection, Mapping mapping) where T : IBase
{
    //... get T.Id or T.Name
}

Otherwise, since there is no shared implementation implicit in the design, you can clumsily assume the properties will be there using dynamic.

public static object GetObjectByIdOrName(this IEnumerable collection, Mapping mapping)
{
    return collection.Cast<dynamic>().FirstOrDefault(x => x.Id == mapping.ObjectId || x.Name == mapping.ObjectName);
}

Upvotes: 4

Related Questions