Do generic functions work well with nullable value types, or do they box behind the scenes?
For example I have a helper function like this:
public static TResult Return<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator, TResult failureValue)
where TInput : class
{
if (o == null) return failureValue;
return evaluator(o);
}
Which I use to offer a fallback value when something is null, eg
var log = person.Return(p => p.log, emptylog)
So depending on whether log
is a value or reference type, do I need a specialised version of Return()
to handle value types without boxing, or is the above good for all cases?
EDIT: I'm curious as to why the author of this http://pastebin.com/vdS1uNu1 has specializations for class -> struct, class -> class, etc.
No, that won't box value types - but it will cause a new native implementation of the method to be created (at JIT time) each time you use a different value type for TResult
, whereas all reference types will share the same native code. That's very rarely a problem though - it's not like it's a per-call overhead. It's that "create the right native code based on the type argument" that allows it to avoid boxing.
See more on this question at Stackoverflow