CSharp - Data Types Dynamic conversions

Introduction

To convert from one type to another and you don't know what the types are until runtime, use Convert class ChangeType method:

public static object ChangeType (object value, Type conversionType);

The source and target types must be one of the base types.

ChangeType accepts an optional IFormatProvider argument. Here's an example:

Demo

using System;
class MainClass/*from   w  w w.  j  a  va 2  s .  c  o m*/
{
   public static void Main(string[] args)
   {
     Type targetType = typeof (int);
     object source = "42";

     object result = Convert.ChangeType (source, targetType);

     Console.WriteLine (result);
     Console.WriteLine (result.GetType());

   }
}

Result

Related Topic