zulfik
zulfik

Reputation: 63

explicit casting of object containing array - to an array

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.

Upvotes: 6

Views: 940

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500425

Assuming you're using .NET 4 (where string.Join gained more overloads) or later there are two simple options:

  • Use dynamic typing to get the compiler to work out the generic type argument:

    dynamic obj = properties.Current.Value;
    string output = string.Join(",", obj);
    
  • Cast to IEnumerable, then use Cast<object> to get an IEnumerable<object>:

    IEnumerable obj = (IEnumerable) properties.Current.Value;
    string output = string.Join(",", obj.Cast<object>());
    

Upvotes: 9

Related Questions