Skip to content

Instantly share code, notes, and snippets.

@SLaks
Created January 19, 2014 14:59
Show Gist options
  • Save SLaks/8506019 to your computer and use it in GitHub Desktop.
Save SLaks/8506019 to your computer and use it in GitHub Desktop.
Non-boxing generic conversions
static void Main()
{
Console.WriteLine(X<int>.GetValue());
Console.WriteLine(X<long>.GetValue());
}
static class X<T> {
static int IntValue = 42;
static long LongValue = 64;
public static T GetValue() {
// Modify this method to run in O(1) allocations (ie, no boxing)
if (typeof(T) == typeof(int))
return (T)(object)IntValue;
else if (typeof(T) == typeof(long))
return (T)(object)LongValue;
else
throw new ArgumentException();
}
}
@SLaks
Copy link
Author

SLaks commented Jan 19, 2014

This source is written to be pasted into LINQPad; if you want to use a regular compiler, you'll need to wrap Main() in a class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment