Skip to content

Instantly share code, notes, and snippets.

@christo8989
Last active October 2, 2019 04:26
Show Gist options
  • Save christo8989/190b885a8b32659f5317378c3200da25 to your computer and use it in GitHub Desktop.
Save christo8989/190b885a8b32659f5317378c3200da25 to your computer and use it in GitHub Desktop.
Maybe<T>
public class Maybe<T>
{
private readonly IEnumerable<T> values;
public T Value
{
get
{
if (!this.HasValue)
{
throw new InvalidOperationException(String.Format("Accessing Maybe<{0}>.Value when there is no value. Try the Maybe<{0}>.ValueOrDefault({0}).", typeof(T)));
}
var result = this.values.First();
return result;
}
}
public bool HasValue
{
get
{
var result = this.values.Any();
return result;
}
}
public Maybe()
{
this.values = new T[0];
}
public Maybe(T value)
{
this.values = IsNull(value) ? new T[0] : new[] { value };
}
public T ValueOrDefault(T defaultValue)
{
var result = this.HasValue ? Value : defaultValue;
return result;
}
public Type GetValueType()
{
var result = typeof(T);
return result;
}
public override int GetHashCode()
{
return HasValue ? Value.GetHashCode() : 0;
}
public override string ToString()
{
return HasValue ? Value.ToString() : "";
}
public static implicit operator Maybe<T>(T value)
{
var result = new Maybe<T>(value);
return result;
}
public static explicit operator T(Maybe<T> value)
{
var result = value.Value;
return result;
}
private bool IsNull(T value)
{
var result = default(T) == null && value == null;
return result;
}
}
public static void Main()
{
//var Type = ((string) null).GetType().ToString();
//Console.WriteLine(Type);
var Type = new Maybe<string>().GetValueType().ToString();
Console.WriteLine(Type);
var foo = new Maybe<string>(null);
Console.WriteLine(foo.ValueOrDefault("Default Value"));
var boo = new Maybe<string>("Value Passed In!");
Console.WriteLine(boo.ValueOrDefault("Default Value"));
boo = "Updated!";
Console.WriteLine(boo);
Maybe<string> fizz = "This is just a string";
Console.WriteLine(fizz);
var fooboo = (String) boo;
Console.WriteLine(fooboo);
var type = boo.GetType();
Console.WriteLine(type);
var valueType = boo.GetValueType();
Console.WriteLine(valueType);
}
/* OUTPUT
System.String
Default Value
Value Passed In!
Updated!
This is just a string
Updated!
Program+Maybe`1[System.String]
System.String
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment