Search code examples
c#genericsnullable

C# how to initialize generic int array with nulls instead of zeros?


If I declare the following:

    public T[] GetFoo<T>(int length)
    {
        return new T[length];
    }

and in client code I call the above like this:

int[] foo = GetFoo<int>(3);

Then foo[] will be initialized like this:

foo[0]=0;
foo[1]=0;
foo[2]=0;

Is there a way that I can have it initialized like this instead?

foo[0]=null;
foo[1]=null;
foo[2]=null;

I ask because '0' has special meaning and I would like to use 'null' instead to indicate that the array element has not been set. Notice that I am using generics, and sometimes I won't be working with int's - for example sometimes I might be working with reference types.


Solution

  • int is a value type which cannot be set to null. If you want to allow for nulls, you must use Nullable<int> as your type parameter, or more succintly int?.

    int?[] foo = GetFoo<int?>(3);