Mega Code Archive

 
Categories / C# Book / 02 Essential Types
 

0320 Dynamic conversions

Convert class provides a ChangeType method: public static object ChangeType (object value, Type conversionType); using System; using System.Text; using System.Globalization; class Sample { public static void Main() { Type targetType = typeof(int); object source = "42"; object result = Convert.ChangeType(source, targetType); Console.WriteLine(result); // 42 Console.WriteLine(result.GetType()); // System.Int32 } } The output: 42 System.Int32