Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A quick example of the use of generics to avoid boxing
public interface ITypeContainer
{
Type ContainedValueType { get; }
IValueContainer<T> ToContainedType<T>();
object ValueAsObject { get; }
}
public interface IValueContainer<T> : ITypeContainer
{
T ContainedValue { get; }
}
public class TypedContainer<T> : ITypeContainer, IValueContainer<T>
{
public Type ContainedValueType { get; }
public T ContainedValue { get; }
public TypedContainer(T contained)
{
this.ContainedValueType = typeof(T);
this.ContainedValue = contained;
}
public IValueContainer<T1> ToContainedType<T1>()
{
return this as IValueContainer<T1>;
}
public object ValueAsObject => ContainedValue;
}
public class ThisOrThat<TThis, TThat>
{
ITypeContainer internalValue;
public ThisOrThat(TThis value)
{
internalValue = new TypedContainer<TThis>(value);
}
public ThisOrThat(TThat value)
{
internalValue = new TypedContainer<TThat>(value);
}
public T Match<T>(Func<TThis, T> thisMatch, Func<TThat, T> thatMatch)
{
if(internalValue.ContainedValueType == typeof(TThis))
{
return thisMatch(((IValueContainer<TThis>)internalValue).ContainedValue);
}
if (internalValue.ContainedValueType == typeof(TThat))
{
return thatMatch(((IValueContainer<TThat>)internalValue).ContainedValue);
}
throw new NullReferenceException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.