Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should a function return?

Tags:

c#

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?
like image 644
user3595338 Avatar asked Jan 19 '26 14:01

user3595338


2 Answers

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?

like image 132
Emond Avatar answered Jan 21 '26 06:01

Emond


Return an empty list. When you return null, you have to check that condition in the code that called func.

like image 40
Oswald Avatar answered Jan 21 '26 07:01

Oswald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!