RSS

Monthly Archives: April 2012

When You Should Initialize Variables Conditionally

Here is an example of a variable you can initalize conditionally.

<pre>        public virtual T QueryString<T>(string name)
        {
            string queryParam = null;
            if (HttpContext.Current != null && HttpContext.Current.Request.QueryString[name] != null)
                queryParam = HttpContext.Current.Request.QueryString[name];

            if (!String.IsNullOrEmpty(queryParam))
                return CommonHelper.To<T>(queryParam);

            return default(T);
        }

now the reason you would want to intialize this conditonally is that no matter what the string is null unless
the if statements are met therefore assigning a value in the begining instead of in the else adds a step to the method that doesn’t have to be there. So do something more like this…

        public virtual T QueryString<T>(string name)
        {
            string queryParam;

            if (HttpContext.Current != null && HttpContext.Current.Request.QueryString[name] != null)
                queryParam = HttpContext.Current.Request.QueryString[name];
            else
                queryParam = null;

            if (!String.IsNullOrEmpty(queryParam))
                return CommonHelper.To<T>(queryParam);

            return default(T);
        }
Advertisements
 
Leave a comment

Posted by on April 18, 2012 in ASP.Net, C#, C# for Beginners

 

Don’t Fear Lambda Expressions

example of a lambda expression

        /// <summary>
        ///     perform a check on the item being added before adding it.
        ///     Return true if it should be added, false if it should not be
        ///     added.
        /// </summary>
        public Func<ICollection<T>, T, bool> BeforeAdd
        {
            get { return _beforeAdd ?? (_beforeAdd = (l, x) => true); }
            set { _beforeAdd = value; }
        }
 
Leave a comment

Posted by on April 18, 2012 in ASP.Net, C#