C# - How do I define an inline method Func<T> as a parameter?

tags2k picture tags2k · Oct 1, 2008 · Viewed 22.7k times · Source

I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method:

public static T GetItem<T>(string key, Func<T> defaultValue)
{
    if (HttpContext.Current.Session[key] == null)
    {
        HttpContext.Current.Session[key] = defaultValue.Invoke();
    }
    return (T)HttpContext.Current.Session[key];
}

Now, how do I actually use this, passing in the Func<T> as an inline method parameter?

Answer

Marc Gravell picture Marc Gravell · Oct 1, 2008

Since that is a func, a lambda would be the simplest way:

Foo foo = GetItem<Foo>("abc", () => new Foo("blah"));

Where [new Foo("blah")] is the func that is invoked as a default.

You could also simplify to:

return ((T)HttpContext.Current.Session[key]) ?? defaultValue();

Where ?? is the null-coalescing operator - if the first arg is non-null, it is returned; otherwise the right hand is evaluated and returned (so defaultValue() isn't invoked unless the item is null).

Finally, if you just want to use the default constructor, then you could add a "new()" constraint:

public static T GetItem<T>(string key)
    where T : new()
{
    return ((T)HttpContext.Current.Session[key]) ?? new T();
}

This is still lazy - the new() is only used if the item was null.