Created
October 26, 2015 01:36
-
-
Save ariesy/eb02e5dcd7c4b65ca336 to your computer and use it in GitHub Desktop.
null object pattern that can use in dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
http://stackoverflow.com/a/22261282/880163 | |
*/ | |
public struct NullObject<T> | |
{ | |
[DefaultValue(true)] | |
private bool isnull;// default property initializers are not supported for structs | |
private NullObject(T item, bool isnull) : this() | |
{ | |
this.isnull = isnull; | |
this.Item = item; | |
} | |
public NullObject(T item) : this(item, item == null) | |
{ | |
} | |
public static NullObject<T> Null() | |
{ | |
return new NullObject<T>(); | |
} | |
public T Item { get; private set; } | |
public bool IsNull() | |
{ | |
return this.isnull; | |
} | |
public static implicit operator T(NullObject<T> nullObject) | |
{ | |
return nullObject.Item; | |
} | |
public static implicit operator NullObject<T>(T item) | |
{ | |
return new NullObject<T>(item); | |
} | |
public override string ToString() | |
{ | |
return (Item != null) ? Item.ToString() : "NULL"; | |
} | |
public override bool Equals(object obj) | |
{ | |
if (obj == null) | |
return this.IsNull(); | |
if (!(obj is NullObject<T>)) | |
return false; | |
var no = (NullObject<T>)obj; | |
if (this.IsNull()) | |
return no.IsNull(); | |
if (no.IsNull()) | |
return false; | |
return this.Item.Equals(no.Item); | |
} | |
public override int GetHashCode() | |
{ | |
if (this.isnull) | |
return 0; | |
var result = Item.GetHashCode(); | |
if (result >= 0) | |
result++; | |
return result; | |
} | |
} | |
var dict = new Dictionary<NullObject<Type>, string>(); | |
dict[typeof(int)] = "int type"; | |
dict[typeof(string)] = "string type"; | |
dict[null] = "null type"; | |
Assert.AreEqual("int type", dict[typeof(int)]); | |
Assert.AreEqual("string type", dict[typeof(string)]); | |
Assert.AreEqual("null type", dict[null]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment