Search code examples
c#.netvisual-studiodynamicobject

how to check if an object is object[0]?


In debug mode, I'm hovering over my variable, and it shows that it is {object[0]}:

enter image description here

However, this IF statement is never getting triggered.

How do I check for this object[0] type?


Solution

  • 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.