You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Babushka/scripts/CSharp/Common/Util/Variant.cs

63 lines
1.6 KiB

using System;
using System.Diagnostics;
namespace Babushka.scripts.CSharp.Common.Util;
public class Variant<T1, T2>
{
private Type _type;
private Object _value;
public Type GetVariantType()
{
return _type;
}
public T GetValue<T>()
{
if (_type != typeof(T))
throw new ArgumentOutOfRangeException(
$"The Variant does not store a {typeof(T)}. The current type is {_type}");
return (T)_value;
}
public void SetValue<T>(T value)
{
if (typeof(T1) != typeof(T) && typeof(T2) != typeof(T))
throw new ArgumentOutOfRangeException(
$"The Variant does not support type {typeof(T)}. Supported types are {typeof(T1)} and {typeof(T2)}");
_type = typeof(T);
_value = value!;
}
public static implicit operator T1(Variant<T1, T2> v)
{
return v.GetValue<T1>();
}
public static implicit operator T2(Variant<T1, T2> v)
{
return v.GetValue<T2>();
}
public static implicit operator Variant<T1, T2>(T1 t)
{
return new Variant<T1, T2> { _type = typeof(T1), _value = t! };
}
public static implicit operator Variant<T1, T2>(T2 t)
{
return new Variant<T1, T2> { _type = typeof(T2), _value = t! };
}
public bool IsType<T>()
{
if (typeof(T1) != typeof(T) && typeof(T2) != typeof(T))
throw new ArgumentOutOfRangeException(
$"The Variant does not support type {typeof(T)}. Supported types are {typeof(T1)} and {typeof(T2)}");
return _type == typeof(T);
}
}