The short version –
Is there an easy way to take a variable of type object containing an instance of an unknown array (UInt16[], string[], etc.) and treat it as an array, say call String.Join(“,”, obj) to produce a comma delimited string?
Trivial? I thought so too.
Consider the following:
object obj = properties.Current.Value;
obj might contain different instances – an array for example, say UInt16[], string[], etc.
I want to treat obj as the type that it is, namely – perform a cast to an unknown type. After I accomplish that, I will be able to continue normally, namely:
Type objType = obj.GetType();
string output = String.Join(",", (objType)obj);
The above code, of course, does not work (objType unknown).
Neither does this:
object[] objArr = (object[])obj; (Unable to cast exception)
Just to be clear – I am not trying to convert the object to an array (it’s already an instance of an array), just be able to treat it as one.
Thank you.
Assuming you’re using .NET 4 (where
string.Joingained more overloads) or later there are two simple options:Use dynamic typing to get the compiler to work out the generic type argument:
Cast to
IEnumerable, then useCast<object>to get anIEnumerable<object>: