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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.