Monday, January 30, 2012

Best Extension Methods: Execute If Not Null

This is very useful extension method.In a situation where we wants to execute a function if object is not null and if null then return some default value in that scenario we can use this extension method. Now we need not to write if..else code for checking null again and again.
///Use it like:
    /// var username = HttpContext.Current.IfNotNull( ctx => ctx.User.IfNotNull( user => user.Identity.IfNotNull( iden => iden.Name ) ) );

    public static TResult IfNotNull(this T target, Func getValue)
    {
        if (target != null)
            return getValue(target);
        else
            return default(TResult);
    }

Compiled By: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates