sapbucket
sapbucket

Reputation: 7195

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.

Upvotes: 2

Views: 2273

Answers (2)

vittore
vittore

Reputation: 17579

NULL can't be of type int.But it can be of type int?. Do int?[] and it will have nulls. As it fills array with default(T) which in case of T int? will be NULL.

Upvotes: 2

dana
dana

Reputation: 18135

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);

Upvotes: 6

Related Questions