Reputation: 3155
I am reading the CLR Via C# book and trying out the example provided.
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct MyNullable<T> where T : struct
{
private readonly bool _hasValue ; //Should be false
private readonly T _value; //Really should be value=default(T)
public MyNullable(T value)
{
_value = value;
_hasValue = true;
}
public bool HasValue {
get { return _hasValue; }
}
public T Value
{
get
{
if (!_hasValue)
{
throw new InvalidOperationException("Nullable object must have a value");
}
return _value;
}
}
public T GetValueOrDefault()
{
return _value;
}
public T GetValueOrDefault(T defaultValue)
{
return !_hasValue ? defaultValue : _value;
}
public override bool Equals(object obj)
{
if (!_hasValue) return obj == null;
if (obj == null) return false;
return _value.Equals(obj);
}
public override int GetHashCode()
{
return !_hasValue ? 0 : _value.GetHashCode();
}
public override string ToString()
{
return _hasValue ? _value.ToString() : "";
}
public static implicit operator MyNullable<T>(T value)
{
return new MyNullable<T>(value);
}
public static explicit operator T(MyNullable<T> value)
{
return value.Value;
}
}
This code is supposed to let me assign a null value to MyNullable as
MyNullable i = null;
but Visual Studio is giving me error message as "Cannot convert source type null to target type MyNullable"
I thought public static implicit operator MyNullable(T value) and
**public static explicit operator T(MyNullable<T> value)**
Did the trick but seemed it's not the case.
Is there any way to make this code work?
Thanks.
Upvotes: 0
Views: 154
Reputation: 117260
As @EricLippert stated in one of his recent blog posts, it is not possible to implement in user code. There are quite a few things happening behind the scenes.
See: http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/
Upvotes: 1