Created
November 23, 2016 02:27
-
-
Save sdedalus/46cfaa42c6dd8cc58ad764a9d5dee343 to your computer and use it in GitHub Desktop.
A quick example of the use of generics to avoid boxing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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