Let's say I have a function like this:
public List<int> func()
{}
Now, for some reason I don't have anything to put into the list, so I will just be returning "something empty". According to a good practice, which one of the following three should I return in the function above?
return null;
return new List<int>();
return default(List<int>); //Is this the same thing as the one above?
Return an empty list:
return new List<int>();
The default(List<int>) will return null; not an empty list!
Returning an empty list prevents excessive null checking after each call to your function. See Is it better to return null or empty collection?
Return an empty list. When you return null, you have to check that condition in the code that called func.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With