How do I avoid boxing/unboxing when extending System.Object?

Posted by Robert H. on Stack Overflow See other posts from Stack Overflow or by Robert H.
Published on 2010-04-09T16:17:01Z Indexed on 2010/04/09 16:43 UTC
Read the original article Hit count: 233

Filed under:
|
|
|
|

I'm working on an extension method that's only applicable to reference types. I think, however, it's currently boxing and unboxing the 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);
        }
    }
}

Example usage:

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET