views:

127

answers:

1

Hi,

I have an Extension Method:

public static string ToDelimenatedString(this object[] array, string delaminator) {...}

The Extension is applied to reference types but not value types. I assume this is because object is nullable. How would I write the method above to target value types, is it even possible without writing it out for each value type?

Cheers,

Rich

+3  A: 

Should work fine with generics:-

public static string ToDelimitedString<T>(this T[] array, string delimiter)

FYI you could [but would likely not want to] do pretty much the inverse to constrain that not to work on value types by saying:

public static string ToDelimitedString<T>(this T[] array, string delimiter)
    where T:class

BTW you'll probably also want to support IEnumerable, posiibly as an overload like this:-

public static string ToDelimitedString<T>(this IEnumerable<T> items, string delimiter)
{
    return string.Join( delimiter, items.Select( item=>item.ToString()).ToArray());
}
Ruben Bartelink
I must be having a bad morning, generics didn't even occur to me. Thanks for your help.
kim3er
NP, happy to help
Ruben Bartelink