anhdung88
anhdung88

Reputation: 11

Casting with Type object

I want to use GetType() method to get the Type of the variable then cast some other variable to this type. For example, I have an Int32 i, a Double d, I want to get Type of d (in general case) then cast i to d's Type then grant i's value to d.

Int32 i = 123;
Double d = 0.0;
Type t = d.GetType();
d = Conversion.CastExamp1 < t > (i);
d = Conversion.ConvertExamp1 < t > (i);

PS: @Zyphrax: i have used your post here Casting a variable using a Type variable but when compiling, it says that "The type or namespace name 't' could not be found...". So could you please describe more detail how to use your code?

Upvotes: 0

Views: 157

Answers (1)

Eric Herlitz
Eric Herlitz

Reputation: 26307

You cannot use Type as a generic parameter, this must be an object that can be constructed which Typecannot. The closes you will get is by using objects as parameters

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 i = 123;
            Double d = 0.0;
            Type t = d.GetType();

            // Print the type of d
            Console.WriteLine(t.Name); // "Double"

            var newI = DoStuff(t, i);

            // Print the new type of i
            Console.WriteLine(newI.GetType().Name); // "Double"
            Console.Read();
        }

        public static object DoStuff(object type, object inData)
        {
            Type newType = (Type)type;

            // Fix nullables...
            Type newNullableType = Nullable.GetUnderlyingType(newType) ?? newType;

            // ...and change the type
            return Convert.ChangeType(inData, newNullableType);
        }
    }
}

Upvotes: 1

Related Questions