Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToList() - ArgumentNullException Handling

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!

like image 814
Sunitha Avatar asked Dec 18 '22 04:12

Sunitha


1 Answers

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

like image 117
Titian Cernicova-Dragomir Avatar answered Jan 04 '23 15:01

Titian Cernicova-Dragomir