Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant I declare a generic list as nullable?

Tags:

Im trying to use the following code:

private Nullable<List<IpAddressRange>> ipAddressRangeToBind; 

But I am getting the following warning:

The type List must be a non-nullable value type in order to use it as a parameter 'T' in the generic type or method 'System.Nullable'.

like image 208
Exitos Avatar asked Sep 14 '11 15:09

Exitos


People also ask

How do you declare as Nullable?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

Is list Nullable in C#?

In C# programs, a List reference can be null. This is not the same as it being empty and having zero elements.

Is a list Nullable?

A list is never null. The variable might be null, but a list itself is not null.

What is default of nullable type?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .


1 Answers

List<T> is already a reference type (for any kind of T) - you can only declare Nullable<T> where T is a non-nullable value type (it's declared as Nullable<T> where T : struct).

But that's okay, because if you just declare:

private List<IpAddressRange> ipAddressRangeToBind; 

then you can still have

ipAddressRangeToBind = null; 

because reference types are always nullable.

like image 85
Jon Skeet Avatar answered Oct 28 '22 03:10

Jon Skeet