Skip to content

Instantly share code, notes, and snippets.

@nicenemo
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicenemo/3fa1e210b1e5fe9c0166 to your computer and use it in GitHub Desktop.
Save nicenemo/3fa1e210b1e5fe9c0166 to your computer and use it in GitHub Desktop.
Either Experiment second try removed Value1, Value2 etc for typed variant casting to object first
using System;
namespace EitherExperiment
{
public static class Either
{
}
public struct Either<T1, T2, T3>
{
private readonly Type selectedType;
private readonly T1 value1;
private readonly T2 value2;
private readonly T3 value3;
public Either()
{
selectedType = null;
value1 = default(T1);
value2 = default(T2);
value3 = default(T3);
}
public Either(T1 value)
{
selectedType = typeof(T1);
value1 = value;
value2 = default(T2);
value3 = default(T3);
}
public Either(T2 value)
{
selectedType = typeof(T2);
value1 = default(T1);
value2 = value;
value3 = default(T3);
}
public Either(T3 value)
{
selectedType = typeof(T3);
value1 = default(T1);
value2 = default(T2);
value3 = value;
}
public T Value<T>()
{
if (HasValue<T1>()) return (T)((object)value1);
if (HasValue<T2>()) return (T)((object)value2);
if (HasValue<T3>()) return (T)((object)value3);
throw new NotSupportedException("Type not supportedException");
}
public T ValueOrDefault<T>()
{
if (HasValue<T1>()) return (T)((object)value1);
if (HasValue<T2>()) return (T)((object)value2);
if (HasValue<T3>()) return (T)((object)value3);
return default(T);
}
public bool HasValue<T>()
{
return typeof(T) == selectedType;
}
public override int GetHashCode()
{
if (selectedType == typeof(T1)) return value1 != null ? value1.GetHashCode() : 0;
if (selectedType == typeof(T2)) return value2 != null ? value2.GetHashCode() : 0;
if (selectedType == typeof(T3)) return value3 != null ? value3.GetHashCode() : 0;
return 0;
}
public override bool Equals(object obj)
{
if (obj == null)
{
return selectedType == null;
}
else
{
var t = obj.GetType();
//REMARK: turning it around and doing obj.Equals(value1) etc,
//because obj is not null does not feel goed, need to write a test that proves that is good/wrong
if (t == selectedType && selectedType == typeof(T1)) return value1 != null ? value1.Equals(obj) : false;
if (t == selectedType && selectedType == typeof(T2)) return value2 != null ? value2.Equals(obj) : false;
if (t == selectedType && selectedType == typeof(T3)) return value3 != null ? value3.Equals(obj) : false;
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment