2

Anyway to optimize this code for null checks?

if (objA != null && objA .Length > 0)
            {
                foreach (var child in objA )
                {
                    if (child.Any != null)
                    {
                        foreach (var a in child.Any)
                        {
                            if (a.Name.ToLower() == "code")
                            {
                                //some code
                            }
                        }
                    }
                }
            }
Jasmine
  • 5,186
  • 16
  • 62
  • 114

1 Answers1

4

I think you want to use the C# 6 null condition ? operator . Here is some psuedo code:

for (int i = 0; i < objA?.Length; i++)
{
    ExecuteCode(objA[i]?.Any);
}    

...

static void ExecuteCode(YourTypeHere[] children)
{
    for (int i = 0; i < children?.Length; i++)
    {
        if (children[i]?.Name?.ToLower() == "code")
        {
            //some code
        }
    }
}

Using a for loop is faster than a foreach: In .NET, which loop runs faster, 'for' or 'foreach'?. Both loops are slightly faster than Linq.

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321