Object Extension Methods for Value Types
I have an extension method:
public static string ToDelimenatedString(this object[] array, string delaminator) {...}
Extension applies to reference types, but not value types. I assume this is because the object is NULL. How can I write the above method for target value types, is it even possible without writing it for each value type?
Greetings,
Rich
+2
source to share
1 answer
Should work fine with generics: -
public static string ToDelimitedString<T>(this T[] array, string delimiter)
FYI, you could [but most likely not want to] do pretty much the inverse to constrain not to work with value types by saying:
public static string ToDelimitedString<T>(this T[] array, string delimiter)
where T:class
By the way, you probably want to support IEnumerable as well, perhaps as an overload such as: -
public static string ToDelimitedString<T>(this IEnumerable<T> items, string delimiter)
{
return string.Join( delimiter, items.Select( item=>item.ToString()).ToArray());
}
+3
source to share