jitm
jitm

Reputation: 2597

C#: returns array from object

There is the next task: I need to check if input parameter (object) is array, then return array of input elements. For example I have input array like this:

int [] array = {1,2,3,4};

And method

  private object[] GetArray(object @from)
  {
  }

So, I need to check in this method that input variable is array and after return this array. For checking I use

if(@from.GetType().IsArray)

And how to create array from object ??? Is it possible ? Thanks.

Upvotes: 1

Views: 15334

Answers (3)

Dan Tao
Dan Tao

Reputation: 128317

If what you want to do is return @from as an object[] -- if it is already an object[] -- then the simplest way is just:

private object[] GetArray(object @from)
{
    return @from as object[] ?? new object[] { @from };
}

The above might look kind of confusing. Here's how it works:

  1. If @from is an object[] to begin with, it just returns that (typed as such).
  2. Other wise, the expression @from as object[] evaluates to null. In this case, the null-coalescing operator (??) evaluates the following expression: new object[] { @from }.

So the result is that this method returns either the already existing object[] array, or an array of length 1 containing @from.

On the other hand, if you want to populate an object[] from the contents of @from, I'd do this:

private object[] GetArray(object @from)
{
    var objects = @from as IEnumerable;
    if (objects != null)
        return objects.Cast<object>().ToArray();

    return new object[] { @from };
}

As LukeH pointed out, you could also check to make sure @from is not a string, if you don't want GetArray(string) to return an object[] containing char elements:

private object[] GetArray(object @from)
{
    var str = @from as string;
    if (str != null)
        return new object[] { str };

    var objects = @from as IEnumerable;
    if (objects != null)
        return objects.Cast<object>().ToArray();

    return new object[] { @from };
}

Upvotes: 4

unholysampler
unholysampler

Reputation: 17321

Without knowing what the object is, creating an array is a very ambiguous task. What values do you want in the array? Do these values have some deeper meaning. These really are things the object should know about itself and you don't necessarily care to know the details.. For example a Collection has a CopyTo method that performs this task.

Upvotes: 0

pankaj
pankaj

Reputation: 8328

you can use arraylist for this task... We can add any object to a arraylist and you can return it then

Upvotes: 0

Related Questions