Convert Type - CSharp System.Reflection

CSharp examples for System.Reflection:Type

Description

Convert Type

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using System.IO;/*  w  ww .j av  a 2 s. co m*/
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        private static object ConvertType(object val, Type fromType, Type toType)
        {
            if (toType.IsEnum())
            {
                toType = Enum.GetUnderlyingType(toType);
            }

            if (toType == typeof(sbyte))
            {
                if (fromType.IsSigned())
                {
                    var l = (long)Convert.ChangeType(val, typeof(long));

                    return (sbyte)l;
                }

                var ul = (ulong)Convert.ChangeType(val, typeof(ulong));

                return (sbyte)ul;
            }

            if (toType == typeof(ushort))
            {
                if (fromType.IsSigned())
                {
                    var l = (long)Convert.ChangeType(val, typeof(long));

                    return (ushort)l;
                }

                var ul = (ulong)Convert.ChangeType(val, typeof(ulong));

                return (ushort)ul;
            }

            if (toType == typeof(uint))
            {
                if (fromType.IsSigned())
                {
                    var l = (long)Convert.ChangeType(val, typeof(long));

                    return (uint)l;
                }

                var ul = (ulong)Convert.ChangeType(val, typeof(ulong));

                return (uint)ul;
            }

            if (toType == typeof(ulong))
            {
                if (fromType.IsSigned())
                {
                    long l = (long)Convert.ChangeType(val, typeof(long));

                    return (ulong)l;
                }

                return Convert.ChangeType(val, typeof(ulong));
            }

            return Convert.ChangeType(val, toType);
        }
        public static Type GetUnderlyingType(this Type t)
        {
            return Nullable.GetUnderlyingType(t);
        }
        public static bool IsSigned(this Type t)
        {
            return
                t == typeof(sbyte) ||
                t == typeof(short) ||
                t == typeof(int) ||
                t == typeof(long);
        }
        public static bool IsEnum(this Type type)
        {
            var info = type.GetTypeInfo();

            return info.IsEnum;
        }
}

Related Tutorials