Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a generic method in C#

Tags:

c#

generics

I am trying to combine a bunch of similar methods into a generic method. I have several methods that return the value of a querystring, or null if that querystring does not exist or is not in the correct format. This would be easy enough if all the types were natively nullable, but I have to use the nullable generic type for integers and dates.

Here's what I have now. However, it will pass back a 0 if a numeric value is invalid, and that unfortunately is a valid value in my scenarios. Can somebody help me out? Thanks!

public static T GetQueryString<T>(string key) where T : IConvertible
{
    T result = default(T);

    if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
    {
        string value = HttpContext.Current.Request.QueryString[key];

        try
        {
            result = (T)Convert.ChangeType(value, typeof(T));  
        }
        catch
        {
            //Could not convert.  Pass back default value...
            result = default(T);
        }
    }

    return result;
}
like image 940
Mike Cole Avatar asked Jan 27 '10 04:01

Mike Cole


3 Answers

What if you specified the default value to return, instead of using default(T)?

public static T GetQueryString<T>(string key, T defaultValue) {...} 

It makes calling it easier too:

var intValue = GetQueryString("intParm", Int32.MinValue); var strValue = GetQueryString("strParm", ""); var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified 

The downside being you need magic values to denote invalid/missing querystring values.

like image 91
Will Avatar answered Oct 11 '22 10:10

Will


I know, I know, but...

public static bool TryGetQueryString<T>(string key, out T queryString) 
like image 42
Jay Avatar answered Oct 11 '22 09:10

Jay


What about this? Change the return type from T to Nullable<T>

public static Nullable<T> GetQueryString<T>(string key) where T : struct, IConvertible
        {
            T result = default(T);

            if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
            {
                string value = HttpContext.Current.Request.QueryString[key];

                try
                {
                    result = (T)Convert.ChangeType(value, typeof(T));  
                }
                catch
                {
                    //Could not convert.  Pass back default value...
                    result = default(T);
                }
            }

            return result;
        }
like image 43
Graviton Avatar answered Oct 11 '22 10:10

Graviton