How to avoid boxing / unpacking when expanding System.Object?

I am working on an extension method that applies only to reference types. I think, however, he is currently boxing and unpacking the value. How can i avoid this?

namespace System
{
    public static class SystemExtensions
    {
        public static TResult GetOrDefaultIfNull<T, TResult>(this T obj, Func<T, TResult> getValue, TResult defaultValue)
        {
            if (obj == null)
                return defaultValue;
            return getValue(obj);
        }
    }
}

Usage example:

public class Foo
{
    public int Bar { get; set; }
}

In some method:

Foo aFooObject = new Foo { Bar = 1 };
Foo nullReference = null;

Console.WriteLine(aFooObject.GetOrDefaultIfNull((o) => o.Bar, 0));  // results: 1
Console.WriteLine(nullReference.GetOrDefaultIfNull((o) => o.Bar, 0));  // results: 0
+3
source share
2 answers

. , , ? , "==", - JIT , . (T, TResult). , . , :

T = string, TResult = int (native code #1)
T = Stream, TResult = byte (native code #2)
T = string, TResult = byte (native code #2)
T = Stream, TResult = string (native code #3)

, , :

public static TResult GetOrDefaultIfNull<T, TResult>
    (this T obj, Func<T, TResult> getValue, TResult defaultValue)
    where T : class

IL , - . , ? , - .

+4

, . , , / (constrained) .

; (JIT , , )

+2

Source: https://habr.com/ru/post/1740482/


All Articles