To check that an object
is a object[]
, your check element is object[]
is already correct.
To check that an object[]
is empty, calling Any()
is already correct, but make sure to call it on the right instance. Avoid that ToEnumerable()
extension method, since it's not doing what you're hoping for.
if (element is object[] && !((object[]) element).Any())
// element is an empty array of objects
Test:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Tester {
static class Program {
static void Test(string name, object element) {
Console.Write($"{name}: ");
Console.WriteLine(element is object[] && !((object[])element).Any());
}
static void Main(string[] args) {
Test("new object()", new object()); // false
Test("new { }", new { }); // false
Test("new object[0]", new object[0]); // true
Test("new object[1]", new object[1]); // false
Test("new List<object>()", new List<object>()); // false
// Note: object[] o = new List<object>(); wouldn't be allowed.
Test("new string[0]", new string[0]); // true
// Note: object[] o = new string[0]; would be allowed.
Test("new int[0]", new int[0]); // false
// Note: object[] o = new int[0]; wouldn't be allowed.
}
}
}
This includes some test cases that could be an indication that the check you're attempting to do isn't a good idea, but it also indicates that it gives accurate results.
There is no object[0]
type. What it's telling you is that it's an empty array of objects.
Have you tried:
var test = element as IEnumerable;
If (test != null && test.Any())
{
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.