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/* w w w.j  ava2 s  .co  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