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:
- If
@from is an object[] to begin with, it just returns that (typed as such).
- 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 };
}