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.
If what you want to do is return
@fromas anobject[]— if it is already anobject[]— then the simplest way is just:The above might look kind of confusing. Here’s how it works:
@fromis anobject[]to begin with, it just returns that (typed as such).@from as object[]evaluates tonull. 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:As LukeH pointed out, you could also check to make sure
@fromis not astring, if you don’t wantGetArray(string)to return anobject[]containingcharelements: