Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object to object[]

Tags:

c#

I have an object whose value may be one of several array types like int[] or string[], and I want to convert it to a string[]. My first attempt failed:

void Do(object value)
{
    if (value.GetType().IsArray)
    {
        object[] array = (object[])value;
        string[] strings = Array.ConvertAll(array, item => item.ToString());
        // ...
    }
}

with the runtime error Unable to cast object of type 'System.Int32[]' to type 'System.Object[]', which makes sense in retrospect since my int[] doesn't contain boxed integers.

After poking around I arrived at this working version:

void Do(object value)
{
    if (value.GetType().IsArray)
    {
        object[] array = ((Array)value).Cast<object>().ToArray();
        string[] strings = Array.ConvertAll(array, item => item.ToString());
        // ...
    }
}

I guess this is OK, but it seems pretty convoluted. Anyone have a simpler way?

like image 486
Rick Mohr Avatar asked Mar 28 '12 15:03

Rick Mohr


People also ask

How do you convert an object to an array of objects?

Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .

What does object [] mean Java?

A Java object is a member (also called an instance) of a Java class. Each object has an identity, a behavior and a state. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created at runtime from templates, which are also known as classes.

How do you change an object into another object?

The first step in converting an object to another is defining a function. Mentioned earlier, a function will accept a type of GoogleLocation and will return an instance of MyLocation . Inside this method we will create a new object of MyLocation and set the values passed from GoogleGeoLocation .

How do you cast an object to an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .


1 Answers

You don't need to convert it to an array and then use LINQ. You can do it in a more streaming fashion, only converting to an array at the end:

var strings = ((IEnumerable) value).Cast<object>()
                                   .Select(x => x == null ? x : x.ToString())
                                   .ToArray();

(Note that this will preserve nulls, rather than throwing an exception. It's also fine for any IEnumerable, not just arrays.)

like image 180
Jon Skeet Avatar answered Oct 08 '22 19:10

Jon Skeet