RSS

When You Should Initialize Variables Conditionally

18 Apr

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

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: