6

Consider the the piece of code below. I need to call the method CreateOrAddToLists() in a loop. First time the method is called the two lists casedata.Cases and casedata.Documents will be null, hence I can populate by assigning cases to casedata.Cases like this:

casedata.Cases = cases;

At any subsequent call to CreateOrAddToLists() lists casedata.Cases and casedata.Documents will not be null and I can add new data to the lists using AddRange():

casedata.Cases.AddRange(cases);

var casedata = new CaseData(); //contains lists to get populated

private void CreateOrAddToLists()
{   
    var cases = new List<Case>(); //gets data with from database
    var documents = new List<Document>(); //gets data with from database

    if (casedata.Cases == null)
    {
        casedata.Cases = cases;
    }
    else
    {
        casedata.Cases.AddRange(cases);
    }
    if (casedata.Documents == null)
    {
        casedata.Documents = documents;
    }
    else
    {
        casedata.Documents.AddRange(documents);
    }
}

Is there a better or neater way to do a null-check before AddRange? Can I do it in on line of code?

hsop
  • 3,546
  • 3
  • 20
  • 19
  • What exactly are you after? It seems okay to me? – James Jan 25 '16 at 11:23
  • 1
    `(casedata.Documents ?? (casedata.Documents = new List())).AddRange(documents);` - but I wouldn't say this is better or neater. Making code smaller doesn't necessarily make it better or more clever - making it readable is more important, because you are the one who will be maintaining it in future – Rhumborl Jan 25 '16 at 11:23

2 Answers2

9

In the constructor for CaseData instantiate the two list objects, then you'll be assured they won't be null and you can just use AddRange.

public CaseData()
{
    Cases = new List<Case>();
    Documents = new List<Document>();
}
Steve
  • 9,335
  • 10
  • 49
  • 81
6

It's more clear:

casedata.Cases = casedata.Cases ?? new List<Case>();
casedata.Cases.AddRange(cases);

casedata.Documents = casedata.Documents ?? new List<Document>();
casedata.Documents.AddRange(documents);
Andrey Burykin
  • 700
  • 11
  • 23
  • I have accepted the answer @Steve provided as it is the more correct answer, but for now in my own code I will use your answer because it is clear and useful and can be easily implemented. – hsop Jan 25 '16 at 11:56