Nullable<T> implementation

ε祈祈猫儿з 提交于 2019-12-01 23:02:12

Assigning null to Nullable<T> is just a syntactic sugar for assigning new Nullable<T>(), it's part of C# language, and you can't add that feature to you custom type.

C# spec,

4.1.10 Nullable types

A nullable type can represent all values of its underlying type plus an additional null value. A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable, and the two forms can be used interchangeably.

6.1.5 Null literal conversions

An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type.

You can't.
Nullable<T> is a special case. It has special processing on CLR level (this isn't a pure C# language feature - in particular, CLR supports special scenarios for boxing/unboxing nullables).

You are declaring your homegrown Nullable as a struct, and a struct is not nullable. You should declare it as a class instead.

this code should throw the same error you are having, switching the Point type declaration from struct to class should fix it.

void Main()
{
    Point p = null;
}

// Define other methods and classes here
struct Point
{
 public int X   {get; set;}
 public int Y   {get; set;}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!