Peter Morris
Peter Morris

Reputation: 23234

Generic parameter problem

I have a business model which consists of a parent/child relationship (Identifier/IdentifierValue) and also some snapshot classes which look the same (IdentifierSnapshot/IdentifierValueSnapshot).

I am trying to create an extension method which will work on an enumeration of either Identifier or IdentifierSnapshot, but I just can't work out what to put in the extension method where I have inserted the XXX placeholder.

//Interfaces
public interface IIdentifier<TIdentifierValue>
  where TIdentifierValue : IIdentifierValue
{
  string Code { get; }
  IEnumerable<TIdentifierValue> GetValues();
}

public interface IIdentifierValue
{
  string Code { get; }
  string Value { get; }
}

//Main classes
public class Identifier : IIdentifier<IdentifierValue>
{
  public string Code { get; set; }
  public IEnumerable<IdentifierValue> GetValues();
}

public class IdentifierValue : IIdentifierValue
{
  public string Code { get; set; }
  public string Value { get; set; }
}

//Snapshots
public class IdentifierSnapshot : IIdentifier<IdentifierValueSnapshot>
{
  public string Code { get; set; }
  public IEnumerable<IdentifierValueSnapshot> GetValues();
}

public class IdentifierValueSnapshot : IIdentifierValue
{
  public string Code { get; set; }
  public string Value { get; set; }
}

public static IdentifierExtensions
{
  public static IEnumerable<XXX> ByCode<XXX>(this IEnumerable<XXX> instance, string code)
  {
    return instance.Where(x => string.Compare(code, x.Code, true) == 0);
  }
}

Upvotes: 0

Views: 69

Answers (1)

David Ruttka
David Ruttka

Reputation: 14409

I think this would do it:

public static IEnumerable<T> ByCode<T,Z>(this IEnumerable<T> instance, string code)
    where T:IIdentifier<Z> 
    where Z:IIdentifierValue

Upvotes: 1

Related Questions