How do you test your Request.QueryString[] variables?

Below is an extension method that will allow you to write code like this: int id = request.QueryString.GetValue<int>(“id”); DateTime date = request.QueryString.GetValue<DateTime>(“date”); It makes use of TypeDescriptor to perform the conversion. Based on your needs, you could add an overload which takes a default value instead of throwing an exception: public static T GetValue<T>(this NameValueCollection … Read more

DateTime.TryParse century control C#

It’s tricky, because the way two digit years work with TryParse is based on the TwoDigitYearMax property of the Calendar property of the CultureInfo object that you are using. (CultureInfo->Calendar->TwoDigitYearMax) In order to make two digit years have 20 prepended, you’ll need to manually create a CultureInfo object which has a Calendar object with 2099 … Read more

Generic TryParse

You should use the TypeDescriptor class: public static T Convert<T>(this string input) { try { var converter = TypeDescriptor.GetConverter(typeof(T)); if(converter != null) { // Cast ConvertFromString(string text) : object to (T) return (T)converter.ConvertFromString(input); } return default(T); } catch (NotSupportedException) { return default(T); } }

Parse v. TryParse

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded. TryParse does not just try/catch internally – the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally … Read more