Skip to content

Instantly share code, notes, and snippets.

@sdedalus
Created November 23, 2016 02:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sdedalus/46cfaa42c6dd8cc58ad764a9d5dee343 to your computer and use it in GitHub Desktop.
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