Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have a look at <a href="http://msdn.microsoft.com/en-us/library/dtb69x08.aspx" rel="nofollow"><code>Convert.ChangeType</code></a> and <a href="http://msdn.microsoft.com/en-us/library/ewtxwhzx.aspx" rel="nofollow"><code>TypeDescriptor.GetConverter</code></a>.</p> <p>I've written an extension method to do this for me:</p> <pre class="lang-cs prettyprint-override"><code>public static T Convert&lt;T&gt;(this object obj) { T result; try { result = (T)System.Convert.ChangeType(obj, typeof(T)); if (object.ReferenceEquals(result, null)) { var typeConverter = !obj.IsNullable() ? TypeDescriptor.GetConverter(typeof(T)) : new NullableConverter(typeof(T)); result = obj is string ? (T)typeConverter.ConvertFromString(obj as string) : (T)typeConverter.ConvertTo(obj, typeof(T)); } } catch (Exception) { result = default(T); } return result; } public static bool IsNullable&lt;T&gt;(this T obj) { return Nullable.GetUnderlyingType(typeof(T)) != null; } </code></pre> <p>Usage:</p> <pre class="lang-cs prettyprint-override"><code>var itemsToConvert = new[] { "4", "5.98", "false", DateTime.Now.ToString() }; var @int = itemsToConvert[0].Convert&lt;int&gt;(); var @double = itemsToConvert[1].Convert&lt;double&gt;(); var @bool = itemsToConvert[2].Convert&lt;bool&gt;(); var @dateTime = itemsToConvert[3].Convert&lt;DateTime&gt;(); Console.WriteLine(@"int: {0}, Type: {1}", @int, @int.GetType()); Console.WriteLine(@"double: {0}, Type: {1}", @double, @double.GetType()); Console.WriteLine(@"bool: {0}, Type: {1}", @bool, @bool.GetType()); Console.WriteLine(@"DateTime: {0}, Type: {1}", @dateTime, @dateTime.GetType()); </code></pre> <p>Output:</p> <blockquote> <p>int: 4, Type: System.Int32<br> double: 5.98, Type: System.Double<br> bool: False, Type: System.Boolean<br> DateTime: 2013/08/21 06:01:07 PM, Type: System.DateTime </p> </blockquote> <p>Hope this helps.</p>
 

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