How to refactor these generic methods?

Posted by Steve Crane on Stack Overflow See other posts from Stack Overflow or by Steve Crane
Published on 2010-03-12T10:27:47Z Indexed on 2010/03/12 10:37 UTC
Read the original article Hit count: 357

Filed under:
|
|

I have written two nearly identical generic extension methods and am trying to figure out how I might refactor them into a single method. They differ only in that one operates on List and the other on List, and the properties I'm interested in are AssetID for AssetDocument and PersonID for PersonDocument. Although AssetDocument and PersonDocument have the same base class the properties are defined in each class so I don't think that helps. I have tried

public static string ToCSVList<T>(this T list) where T : List<PersonDocument>, List<AssetDocument>

thinking I might then be able to test the type and act accordingly but this results in the syntax error

Type parameter 'T' inherits conflicting constraints

These are the methods that I would like to refactor into a single method but perhaps I am simply going overboard and they would besat be left as they are. I'd like to hear what you think.

public static string ToCSVList<T>(this T list) where T : List<AssetDocument>
{
  var sb = new StringBuilder(list.Count * 36 + list.Count);
  string delimiter = String.Empty;

  foreach (var document in list)
  {
    sb.Append(delimiter + document.AssetID.ToString());
    delimiter = ",";
  }

  return sb.ToString();
}

public static string ToCSVList<T>(this T list) where T : List<PersonDocument>
{
  var sb = new StringBuilder(list.Count * 36 + list.Count);
  string delimiter = String.Empty;

  foreach (var document in list)
  {
    sb.Append(delimiter + document.PersonID.ToString());
    delimiter = ",";
  }

  return sb.ToString();
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics