Does an empty array in .NET use any space?

后端 未结 9 1510
暗喜
暗喜 2021-01-01 10:39

I have some code where I\'m returning an array of objects.

Here\'s a simplified example:

string[] GetTheStuff() {
    List s = null;
             


        
9条回答
  •  自闭症患者
    2021-01-01 11:16

    Others have answered your question nicely. So just a simple point to make...

    I'd avoid returning an array (unless you can't). Stick with IEnumerable and then you can use Enumerable.Empty() from the LINQ APIs. Obviously Microsoft have optimised this scenario for you.

    IEnumerable GetTheStuff()
    {
        List s = null;
        if (somePredicate())
        {
            var stuff = new List();
            // load data
            return stuff;
        }
    
        return Enumerable.Empty();
    }
    

提交回复
热议问题