Managing empty/null Lists

Viewed 62

I'm developing a webapi in Asp Core 3.1. I have a class like this:

public class Employee
{
    public string name { get; set; }
    public string surname { get; set; }
    public List<Contact> contacts { get; set; }
}

in the Get action inside the EmployeeController I'm doing something like this:

var emp = new DTO.EmployeeDetails();
emp = await getEmployeeBaseData(id);

if (emp == null)
    return NotFound();

emp.contacs = await getContats(id);

The problem comes when the employee has no contats:

System.NullReferenceException: Object reference not set to an instance of an object.

I tried initializing the List like:

emp.contacs = new List<Contact>();
emp.contacs = await getContats(id);

The only things actually working is:

try
{
    emp.contacs = await getContats(id);
}
catch (NullReferenceException)
{
    Console.WriteLine("No contacs for id: " + id);
}

Which is very ugly.

I can't assign null to a list. I can't assign an empty enumerable. what can I do?

edit: Sorry if I wrote the question too abstract or generic. This is the getcontacs method:

private async Task<List<Contact>> getContats(int? id)
{
    return await DAL.DataAccess.LoadDataAsync<Contact>(_ConnString,
        "SELECT * FROM contacs WHERE id = @id",
        new { id = id });
}

And this is the LoadDataAsync used inside of it (it's a simple DAL using Dapper):

public static async Task<List<T>> LoadDataAsync<T>(string conn, string sql, T data)
{
    using (IDbConnection cn = new SqlConnection(conn))
    {
        cn.Open();
        var res = await cn.QueryAsync<T>(sql, data);
        return res.ToList();
    }
}
0 Answers
Related