开发者

Why cant I declare a generic list as nullable?

Im trying to use the following code:

private Nullable<List<IpAddressRange>> ipAddressRangeToBind;

But I am getting the following w开发者_开发技巧arning:

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'.


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.


List<IpAddressRange> is a reference type - it is already nullable - in fact it will be initialized to null by that declaration.


You can just use it as is:

List<IpAddressRange> ipAddressRangeToBind = null;  

List is already nullable.


Reference types cannot be wrapped in Nullable<T> due to a where T : struct constraint on the generic.

The reasons for this constraint are:

  1. Reference types are already nullable by definition, and
  2. Nullable is not very space efficient, but more a "logical" nullability.

Nullable<T> has a bool property HasValue and a type T property Value which contains the actual value-type value.

Even if HasValue == false (that is, if the nullable wrapped variable is set to null), you STILL consume the space for the value type as if it was there.

It's logically nullable to allow you to specify optional behavior, but it doesn't save any space. This is very similar to how boost::optional works in C++.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜