Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a simple version:</p> <pre><code>object ConvertToAny(string input) { int i; if (int.TryParse(input, out i)) return i; double d; if (double.TryParse(input, out d)) return d; return input; } </code></pre> <p>It will recognize ints and doubles, but everything else is returned as a string. The problem with handling enums is that there's no way to know what enum a value belongs to and there's no way to tell whether it should be a string or not. Other problems are that it doesn't handle dates/times or decimals (how would you distinguish them from doubles?), etc.</p> <p>If you're willing to change your code like this:</p> <pre><code>PropertyInfo info = typeof(MyObject).GetProperty("SomeProperty"); info.SetValue(obj, AwesomeFunction("20.53", info.PropertyType), null); </code></pre> <p>Then it becomes substantially easier:</p> <pre><code>object ConvertToAny(string input, Type target) { // handle common types if (target == typeof(int)) return int.Parse(input); if (target == typeof(double)) return double.Parse(input); ... // handle enums if (target.BaseType == typeof(Enum)) return Enum.Parse(target, input); // handle anything with a static Parse(string) function var parse = target.GetMethod("Parse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, new[] { typeof(string) }, null); if (parse != null) return parse.Invoke(null, new object[] { input }); // handle types with constructors that take a string var constructor = target.GetConstructor(new[] { typeof(string) }); if (constructor != null) return constructor.Invoke(new object[] { input }); } </code></pre> <p>Edit: Added a missing parenthesis</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload