Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a TypeCode to an actual type?

Tags:

c#

types

In the code below I get colType which is a code number for the type. But how would I convert that number into the actual type? Thx!!

for (int j = 0; j < dvColumns.Count; j++)
{
    // Get the name of the column.
    drvCols = dvColumns[j];
    colName = drvCols.Row.ItemArray[3].ToString();

    // Get columns data type code and save it off.
    colType = Convert.ToInt32(drvCols.Row.ItemArray[11]);
}
like image 583
user259286 Avatar asked May 06 '11 18:05

user259286


2 Answers

It's even simpler:

Type type = Type.GetType("System." + colType);

If you want to convert a value to that type you can use the typecode directly

Convert.ChangeType(value, colType);
like image 141
schoetbi Avatar answered Oct 11 '22 16:10

schoetbi


Using a switch statement:

    public static Type ToType(this TypeCode code)
    {
        switch (code)
        {
            case TypeCode.Boolean:
                return typeof(bool);

            case TypeCode.Byte:
                return typeof(byte);

            case TypeCode.Char:
                return typeof(char);

            case TypeCode.DateTime:
                return typeof(DateTime);

            case TypeCode.DBNull:
                return typeof(DBNull);

            case TypeCode.Decimal:
                return typeof(decimal);

            case TypeCode.Double:
                return typeof(double);

            case TypeCode.Empty:
                return null;

            case TypeCode.Int16:
                return typeof(short);

            case TypeCode.Int32:
                return typeof(int);

            case TypeCode.Int64:
                return typeof(long);

            case TypeCode.Object:
                return typeof(object);

            case TypeCode.SByte:
                return typeof(sbyte);

            case TypeCode.Single:
                return typeof(Single);

            case TypeCode.String:
                return typeof(string);

            case TypeCode.UInt16:
                return typeof(UInt16);

            case TypeCode.UInt32:
                return typeof(UInt32);

            case TypeCode.UInt64:
                return typeof(UInt64);
        }

        return null;
    }
like image 25
cwills Avatar answered Oct 11 '22 14:10

cwills