Does an empty array in .NET use any space?

后端 未结 9 1534
暗喜
暗喜 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:19

    This is not a direct answer to your question.

    Read why arrays are considered somewhat harmful. I would suggest you to return an IList in this case and restructure the code a little bit:

    IList GetTheStuff() {
        List s = new List();
        if( somePredicate() ) {
            // imagine we load some data or something
        }
        return s;
    }
    

    In this way the caller doesn't have to care about empty return values.


    EDIT: If the returned list should not be editable you can wrap the List inside a ReadOnlyCollection. Simply change the last line to. I also would consider this best practice.

        return new ReadOnlyCollection(s);
    

提交回复
热议问题