105

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;
}
4
  • 1
    He is porting a bunch of implementations, so call the old functionality, remember the result, call the new functionality, remember the result, compare. Now do that 100 times with a bunch of random inputs, and voila! Commented Jan 27, 2010 at 4:16
  • I'm sorry, I still don't understand how that applies in this case. I am still trying to get the function to work.
    – Mike Cole
    Commented Jan 27, 2010 at 4:18
  • Looking at the answers, I'm a bit confused: are your callers parameterizing using int or int? as T?
    – user24359
    Commented Jan 27, 2010 at 4:38
  • It seems to me like, instead of handling this internally, you should be allowing the method to throw the exception. Maybe that's just me, but someone might be confused why their call is always returning the default value since they aren't seeing the exception that is generated when ChangeType fails.
    – crush
    Commented Feb 16, 2015 at 20:27

6 Answers 6

79

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.

3
  • Yes, this seems more viable than relying on the default value of an integer. I'll keep this in mind. I'm still hoping to get my original function working for all types, although I just may resort to using non-generic functions.
    – Mike Cole
    Commented Jan 27, 2010 at 14:40
  • Why not just return something other than zero for an invalid integer? You could return anything you want that isn't either a valid value or already have a special purpose, like null. You could even create create your own type called InvalidInteger or something. You are returning null for a bad querystring, right? You could return that too for an invalid integer, so null would mean simply 'something is bad and i have no value for you', and maybe pass a reasonCode by reference to the function? Commented May 12, 2014 at 19:09
  • 1
    How to to get value for : long ? test where default should be null Commented Jul 3, 2014 at 19:30
17

I know, I know, but...

public static bool TryGetQueryString<T>(string key, out T queryString)
8
  • 4
    The Try-pattern should be well known to any .NET developer. It is not a bad thing if you ask me. In F# or NET 4.0 you would use Option (or Choice) Commented Jan 27, 2010 at 5:17
  • 8
    If for no other reason, I try to avoid it because I hate having to "pre-declare" that output variable, especially if it never even gets used -- a waste of what could otherwise have been a perfectly good line of code.
    – Jay
    Commented Jan 27, 2010 at 5:19
  • 1
    I hate the Try pattern for the same reason as Jay stated. I would prefer one generic function if possible, which was my original goal.
    – Mike Cole
    Commented Jan 27, 2010 at 14:38
  • 12
    Do or do not, there is no try! <Yoda>
    – Rabbit
    Commented Feb 6, 2014 at 6:36
  • 1
    @Jay In C#7 you no longer have to pre-daclare: blogs.msdn.microsoft.com/dotnet/2016/08/24/…
    – Holf
    Commented Sep 30, 2016 at 13:47
17

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;
        }
6
  • Error: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'.
    – Mike Cole
    Commented Jan 27, 2010 at 4:16
  • 1
    You also need to specify where T : struct.
    – Aaronaught
    Commented Jan 27, 2010 at 4:17
  • @Mike C: You should not be getting the same error. The edited code definitely compiles.
    – Aaronaught
    Commented Jan 27, 2010 at 4:28
  • Yup, got it now. So what happens when I want to call this for the String type? It won't accept it as is now.
    – Mike Cole
    Commented Jan 27, 2010 at 4:52
  • @MikeC, don't think that's possible because string is a nullable value
    – Graviton
    Commented Jan 27, 2010 at 8:44
5

Convert.ChangeType() doesn't correctly handle nullable types or enumerations in .NET 2.0 BCL (I think it's fixed for BCL 4.0 though). Rather than make the outer implementation more complex, make the converter do more work for you. Here's an implementation I use:

public static class Converter
{
  public static T ConvertTo<T>(object value)
  {
    return ConvertTo(value, default(T));
  }

  public static T ConvertTo<T>(object value, T defaultValue)
  {
    if (value == DBNull.Value)
    {
      return defaultValue;
    }
    return (T) ChangeType(value, typeof(T));
  }

  public static object ChangeType(object value, Type conversionType)
  {
    if (conversionType == null)
    {
      throw new ArgumentNullException("conversionType");
    }

    // if it's not a nullable type, just pass through the parameters to Convert.ChangeType
    if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
      // null input returns null output regardless of base type
      if (value == null)
      {
        return null;
      }

      // it's a nullable type, and not null, which means it can be converted to its underlying type,
      // so overwrite the passed-in conversion type with this underlying type
      conversionType = Nullable.GetUnderlyingType(conversionType);
    }
    else if (conversionType.IsEnum)
    {
      // strings require Parse method
      if (value is string)
      {
        return Enum.Parse(conversionType, (string) value);          
      }
      // primitive types can be instantiated using ToObject
      else if (value is int || value is uint || value is short || value is ushort || 
           value is byte || value is sbyte || value is long || value is ulong)
      {
        return Enum.ToObject(conversionType, value);
      }
      else
      {
        throw new ArgumentException(String.Format("Value cannot be converted to {0} - current type is " +
                              "not supported for enum conversions.", conversionType.FullName));
      }
    }

    return Convert.ChangeType(value, conversionType);
  }
}

Then your implementation of GetQueryString<T> can be:

public static T GetQueryString<T>(string key)
{
    T result = default(T);
    string value = HttpContext.Current.Request.QueryString[key];

    if (!String.IsNullOrEmpty(value))
    {
        try
        {
            result = Converter.ConvertTo<T>(value);  
        }
        catch
        {
            //Could not convert.  Pass back default value...
            result = default(T);
        }
    }

    return result;
}
5

You can use sort of Maybe monad (though I'd prefer Jay's answer)

public class Maybe<T>
{
    private readonly T _value;

    public Maybe(T value)
    {
        _value = value;
        IsNothing = false;
    }

    public Maybe()
    {
        IsNothing = true;
    }

    public bool IsNothing { get; private set; }

    public T Value
    {
        get
        {
            if (IsNothing)
            {
                throw new InvalidOperationException("Value doesn't exist");
            }
            return _value;
        }
    }

    public override bool Equals(object other)
    {
        if (IsNothing)
        {
            return (other == null);
        }
        if (other == null)
        {
            return false;
        }
        return _value.Equals(other);
    }

    public override int GetHashCode()
    {
        if (IsNothing)
        {
            return 0;
        }
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        if (IsNothing)
        {
            return "";
        }
        return _value.ToString();
    }

    public static implicit operator Maybe<T>(T value)
    {
        return new Maybe<T>(value);
    }

    public static explicit operator T(Maybe<T> value)
    {
        return value.Value;
    }
}

Your method would look like:

    public static Maybe<T> GetQueryString<T>(string key) where T : IConvertible
    {
        if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
        {
            string value = HttpContext.Current.Request.QueryString[key];

            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                //Could not convert.  Pass back default value...
                return new Maybe<T>();
            }
        }

        return new Maybe<T>();
    }
0

I like to start with a class like this class settings { public int X {get;set;} public string Y { get; set; } // repeat as necessary

 public settings()
 {
    this.X = defaultForX;
    this.Y = defaultForY;
    // repeat ...
 }
 public void Parse(Uri uri)
 {
    // parse values from query string.
    // if you need to distinguish from default vs. specified, add an appropriate property

 }

This has worked well on 100's of projects. You can use one of the many other parsing solutions to parse values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.