Jackie
This is a very common requirement in the world of web development, and, as you already noted, there is no built-in way to achieve this, but that is not so simple in this case.
@Chris these rules are not arbitrary with a single shot of imagination. They are actually very common when it comes to user input, especially on the Internet. In fact, logical conversions are also quite common given that checkboxes in ASP.NET return on / off (for some reason).
You have a couple of options. One is a simplified approach, and the other is an extensible solution. It all starts with how you would like to use this functionality from your application. Since you did not shed much light on what you are doing now, or how you would like to do it, I have allowed me to make several assumptions.
The primary assumption is that values ββcome to you through Request.Form or Request.QueryStrings (both of them are NameValueCollections, which may contain multiple values ββfor a given name).
Suppose you need a method called ChangeType that sets the parameters name, and the type you want to change will return the value as the required type. Thus, the signature of the method may look like this:
public T ChangeType<T>(string parameterName, T defaultValue = default(T))
So you can use it like this:
int someId = ChangeType<int>("id", -1);
Thus, the value of the someId variable will be either the value extracted from Request.Form, or Request.QueryStrings as int (if it exists), or -1 if it is not.
A more complete implementation is as follows:
static T ChangeType<T>(string value) where T: struct { Type typeOft = typeof(T); if (String.IsNullOrEmpty(value.Trim())) return default(T); if (typeOft == typeof(Int32)) return (T)ConvertToInt32(value); else if (typeOft == typeof(Int64)) return (T)ConvertToInt64(value); else if (typeOft == typeof(Double)) return (T)ConvertToDouble(value); else if (typeOft == typeof(Decimal)) return (T)ConvertToDecimal(value); return default(T); } static object ConvertToInt32(string value) { return Int32.Parse(value, NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint); } static object ConvertToInt64(string value) { return Int64.Parse(value, NumberStyles.Currency ^ NumberStyles.AllowDecimalPoint); } static object ConvertToDouble(string value) { return Double.Parse(value, NumberStyles.Currency); } static object ConvertToDecimal(string value) { return Decimal.Parse(value, NumberStyles.Currency); }
If you need to be able to handle more types, just execute the required method (for example, ConvertToInt32, for example) and add one more condition to the ChangeType<T> method, and you are done.
Now, if you are looking for an extensible solution so that you can add additional features without changing the source code and not being able to process your own custom types, please take a look at this blog post. [ChangeType - changing the type of a variable in C #] [1] http://www.matlus.com/2010/11/changetypet-changing-the-type-of-a-variable-in-c/
Hope this helps.