I have an extension method that I would like to overload so it can handle both reference types and nullable value types. When I try to do this, however, I get "Member with the same signature is already declared." Can C# not use the where
qualifier on my generic methods to distinguish them from each other? The obvious way to make this work is to give each method a distinct name, but this doesn't seem like a very elegant solution to me. What is the best way of making this work?
Example:
public static T Coalesce<T>(this SqlDataReader reader, string property) where T : class
{
return reader.IsDBNull(reader.GetOrdinal(property))
? null
: (T) reader[property];
}
public static T? Coalesce<T>(this SqlDataReader reader, string property) where T : struct
{
return reader.IsDBNull(reader.GetOrdinal(property))
? null
: (T?)reader[property];
}
// Usage
var id = reader.Coalesce<System.Guid?>("OptionalID");