Overloading the reference and null support method

I have an extension method that I would like to overload so that it can handle both reference types and nullable value types. However, when I try to do this, I get: "A member with the same signature has already been announced." Can C # not use a qualifier where

for my common methods to differentiate them from each other? The obvious way to make this work is to give each method a different name, but that doesn't seem like a very elegant solution to me. What's the best way to make 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");

      

+2


source to share


2 answers


This works if the property type is SqlDataReader.Item[string]

object

.



public static T Coalesce<T>(this SqlDataReader reader, string property)
{
    return reader.IsDBNull(reader.GetOrdinal(property))
               ? default(T)
               : (T) reader[property];
}

      

+7


source


As @ 280Z28 pointed out , in your case, you can handle both cases in the same way. However, if you really want two methods with the same signature, but with different internals based on the pass-in type, this is not possible in C #.

From Differences Between C ++ and C # Generics Templates on MSDN:



  • C # does not support explicit specialization; that is, a custom implementation of a template for a specific type.
  • C # does not support partial specialization: a custom implementation for a subset of type arguments.
+2


source







All Articles