ToList() - ArgumentNullException Handling

12.8k views Asked by At

Hi I have a class named Activity,

On a form I create its object array as,

 Activity[] _actList; 

And then do this,

List<Activity> termsList = _actList.ToList<Activity>();

since _actiList is null its throwing the ArgumentNullException.

So my question is,

How can I handle this exception?
Or is there a work around to get the same functionality ?

Please Help!

3

There are 3 answers

2
Titian Cernicova-Dragomir On BEST ANSWER

You need to check for null before calling ToList

var termsList = _actList == null ? null : _actList.ToList(); 

If you are using the C# 6.0 or later you can write the same in a shorter way:

var termsList = _actList?.ToList(); 

You could also catch the exception, but I don't recommend that in this case especially if it is a common scenario for the array to be null

2
Armin Cheng On

You could make sure that the array is never null with assigning an empty default array.

Activity[] _actList = new Activity[] { };

so, when the form is initialized the array also will be initialized with an empty array. If you are doing .ToList() now, you will get an empty list then instead of an exception.

0
Neville Nazerane On

Using try catch which would work for any such issue:

try {
    List<Activity> termsList = _actList.ToList<Activity>();
}
catch(ArgumentNullException){

}

Or you can use set a default value if it is null using the ?? operator:

List<Activity> termsList = (_actList ?? new Employee[] { }).ToList<Activity>();

This would give you an empty list if your array is empty.