I didn't know what better title to chose for the question as I don't know what's the problem. Consider the following small C# code:
static void Main(string[] args)
{
F1(null);
}
public static void F1(int[] values)
{
F2(1, values?[0] as object ?? new object[0]);
F2(2, values?.Select(v => (object)v) ?? new object[0]);
F2(3, values?.Select(v => (object)v).ToArray() ?? new object[0]);
}
public static void F2(int idx, params object[] values)
{
Console.WriteLine($"count {idx}: '{values?.Count()}'");
}
It outputs:
count 1: '1'
count 2: '1'
count 3: '0'
Why the first 2 are 1? If I use the Immediate Window in Visual Studio, all the following are null:
values?[0]
null
values?.Select(v => (object)v)
null
values?.Select(v => (object)v).ToArray()
null
As you might know, for a
paramsparameter of typeobject[], you can either pass an expression of typeobject(which implicitly creates aobject[]and theobjectyou passed will be treated as an element of the array), or an expression of typeobject[](which will be passed to the method "directly").Notably, this depends on the compile-time type of the expression only (unless there is
dynamicstuff going on). Therefore, an expression of typeobjectwill be wrapped in an array, even if the expression evaluates to anobject[]object at runtime.With that in mind, it should be clear why your code behaves like that. Both of these expressions are of type
object:values?[0] as objectis of typeobject, andvalues?.Select(v => (object)v)is of typeIEnumerable<object>. But the right hand side of??is of typeobject[]. So the whole expression is of typeobjectin both cases.In the case of
values?.Select(v => (object)v).ToArray()is of typeobject[], the same type asnew object[0], so the whole expression is of typeobject[].