6

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.

2
  • 1
    Try to convert the object to IEnumerable Commented Dec 13, 2012 at 8:32
  • 1
    Maybe you can replace object obj = properties.Current.Value; by dynamic obj = properties.Current.Value; then treat obj as an array? Commented Dec 13, 2012 at 8:34

1 Answer 1

9

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>());
    
Sign up to request clarification or add additional context in comments.

1 Comment

You are my god! Thank you :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.