Question

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

Was it helpful?

Solution

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());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top