I am trying to implement Nullable type. But below mentioned code doesn\'t support null value for valuetype datatypes.
using System;
using System.Runtime;
using S
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 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;}
}
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).