Home > Net >  Check null/empty at multiple levels using question mark operator c#
Check null/empty at multiple levels using question mark operator c#

Time:05-26

Consider I have the following class

class Dummy
{
    List<DummyObj> list;
}

class DummyObj
{
    string A;
    int B;
}

I have a Helper Class which takes in an object of type Dummy and returns the value of A present at index 0 of list. I'm trying to handle all null and empty cases (when passed in dummy is null, when dummy is not null, but list is not initialized, when list is initialized but it's empty.

public string GetA(Dummy dummy)
{
    return dummy?.list?[0]?.A;
}

It works fine when dummy is null or list is null. But when list is empty, I get the following error - System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')'

I'm definitely making some mistake handling empty list. Can someone please point it out and help me fix the above statement?

Edit: To clarify, I would like to return a null in case any of the above conditions hold true.

CodePudding user response:

Use the following:

return dummy?.list?.FirstOrDefault()?.A;

You should avoid using index on a List as Lists aren't deterministic. If you have to know the position of an item in an a collection, use an array.

  • Related