Created
January 19, 2014 14:59
-
-
Save SLaks/8506019 to your computer and use it in GitHub Desktop.
Non-boxing generic conversions
This file contains hidden or 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
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.