array = null or array.length = 0

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rene

    array = null or array.length = 0

    I have an array that may or may not contain data during the course of its
    life. When I first instantiate my class level array reference I set the
    array to null:
    int[] xyz = null;
    But I am thinking of initializing it to zero
    int[] xyz = new int[0]

    There is no good reason why I need to do this except that it feels more
    accurate to say that an array contains zero items rather than null.

    Can anyone share some opinions on why I should go one way versus another?
    Performance issues, good practices, etc?

    Thank you.


  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: array = null or array.length = 0

    Rene,

    From a performance standpoint, you want to use null, because you would
    always have this object reference hanging around. Of course, in the scheme
    of things, it's probably insignificant, so I wouldn't even say that this is
    a good reason to use null.

    I think that what you should do is encapsulate access to the variable in
    a property, and make the variable private. This way, when someone assigns
    to the variable, if the length of the array is zero, or null, you can set it
    to a consistent state in the private variable. This way, when you return
    the private variable through the property, you can be assured it is always
    returning what you want (a null value, or an array with length zero).

    Hope this helps.

    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m

    "Rene" <nospam@nospam. nospam> wrote in message
    news:uBhzF72jEH A.384@TK2MSFTNG P10.phx.gbl...[color=blue]
    >I have an array that may or may not contain data during the course of its
    > life. When I first instantiate my class level array reference I set the
    > array to null:
    > int[] xyz = null;
    > But I am thinking of initializing it to zero
    > int[] xyz = new int[0]
    >
    > There is no good reason why I need to do this except that it feels more
    > accurate to say that an array contains zero items rather than null.
    >
    > Can anyone share some opinions on why I should go one way versus another?
    > Performance issues, good practices, etc?
    >
    > Thank you.
    >
    >[/color]


    Comment

    Working...