ChangeType, Convert - Convert from one type to another

I looked at various options that seem to be available on the .NET platform (I think). In particular, I reviewed 1. TypeConverter 2. Convert.Toxxx 3. Convert.ChangeType

Each of them for one reason or another does not work for me. I am completely surprised that in the .NET Framework there is no such solution for this kind of thing. I guess I'm not the only one who needs it;)

Here is what I am trying to do. In fact, I have a bunch of html forms that are used in the application. These forms allow users to enter data (obviously), and I need to extract this data into various data types.

These data types are simple types, primitive types, value types, reference types, and custom link types. In other words: 1. Int32, Int64, double, decimal, DateTime, etc. 2. Int32 [], double [], string [] and, possibly, other arrays of primitive types 3. various custom DTO objects that have the above properties as properties.

The "input" in the form of a string is usually since I am in the land of Http. To give you an idea of ​​why existing solutions don't work for me, take a look at the following "string" inputs that need conversion

  • "1,234" β†’ Int32
  • "$ 1,234" β†’ Int32
  • "$ 1,234" β†’ Int32
  • "" β†’ Int32
  • "1,2,3,4,5" β†’ Int32 []
  • "0" OR "false" OR "False" OR "off" β†’ Boolean false

I know how to convert each of these cases manually, but I’m either looking for a part of the part of the framework that I skipped or a decent solution that handles the types of inputs listed above.

+1
types
source share
2 answers

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.

+1
source share

All primitive types, such as int and bool, have a TryParse static method that you can use for them. This will make your Int32 stuff for you:

 Int32 temp = 0; Int32.TryParse(myStringInput, out temp); 

TryParse() returns a boolean value indicating whether the parsing was successful or not, so you can check it and take action if you want, or just do what I did above and have a default value if TryParse fails . TryParse is especially useful because it does not throw an exception if it fails (it just returns false ).

bool.TryParse() will not directly convert the numeric value 0 to false - you need to pass it to a string first:

 bool x = true; bool.TryParse(0.ToString(), out x); Console.WriteLine("x is {0}", x); 

When translating a string value into a boolean value or its value, your own function is required to interpret it.

+1
source share

All Articles