3

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 System.Runtime.InteropServices;

namespace Nullable
{

    [Serializable, StructLayout(LayoutKind.Sequential)]    
    public struct Nullable<T> where T : struct
    {
        private bool hasValue;

        public bool HasValue
        {
            get { return hasValue; }
        }

        internal T value;

        public Nullable(T value)
        {
            this.value = value;
            this.hasValue = true;
        }

        public T Value
        {
            get
            {
                if (!this.hasValue)
                {
                    new InvalidOperationException("No value assigned");
                }
                return this.value;
            }
        }

        public T GetValueOrDefault()
        {
            return this.value;
        }

        public T GetValueOrDefault(T defaultValue)
        {
            if (!this.HasValue)
            {
                return defaultValue;
            }
            return this.value;

        }

        public override bool Equals(object obj)
        {
            if (!this.HasValue)
            {
                return obj == null;
            }
            if (obj == null)
            {
                return false;
            }
            return this.value.Equals(obj);
        }

        public override int GetHashCode()
        {
            if (!this.hasValue)
            {
                return 0;
            }
            return this.value.GetHashCode();
        }

        public override string ToString()
        {
            if (!this.hasValue)
            {
                return string.Empty;
            }
            return this.value.ToString();
        }

        public static implicit operator Nullable<T>(T value)
        {
            return new Nullable<T>(value);
        }

        public static explicit operator T(Nullable<T> value)
        {
            return value.Value;
        }
    }
}

When I trying to assign the value as null, it's throwing an error "Cannot convert null to 'Nullable.Nullable' because it is a non-nullable value type"

What I have to do to resolve this issue?

Karthick NS
  • 88
  • 1
  • 7
  • 6
    why do you want to re-invent the wheel ? – Selman Genç Sep 02 '14 at 17:41
  • It's impossible to create a `Nullable` type with the same functionality as the .NET type for several reasons. This is just one of them. – Servy Sep 02 '14 at 17:44
  • 2
    just am trying to learn, how they are implemented in the framework – Karthick NS Sep 02 '14 at 17:44
  • I'm pretty sure the compiler and runtime have some 'special case' implementation to handle this specifically for the system provided Nullable types, and you can not re-implement them yourself. – CodingWithSpike Sep 02 '14 at 17:48
  • 1
    here is something you can take notes from [nullable.cs](http://referencesource.microsoft.com/#mscorlib/system/nullable.cs.html) – RadioSpace Sep 02 '14 at 18:29

3 Answers3

7

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.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2

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

Dennis
  • 37,026
  • 10
  • 82
  • 150
1

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;}
}
Ismail Hawayel
  • 2,167
  • 18
  • 16