asa
asa

Reputation: 779

Identify object type and pass it the fuction typeof() at runtime

I'm trying to create a method that should get a generic class as parameter and return a datatable based on its fields.

The method I have so far is:

    public DataTable TranformClassIntoDataTable<T>(T GenericClass)
    {
        DataTable dt = new DataTable();

        Type objType = typeof(T);
        FieldInfo[] info = objType.GetFields();

        if (info.Length != 0)
        {
            for (int i = 0; i < info.Length; i++)
            {
                // PROBLEM HERE: the part inside of the typeof() isn't accepted by C#
                dt.Columns.Add(info[i].Name, typeof(info[i].GetType()); 
            }
        }
        else
        {
            throw new ArgumentException("No public fields are defined for the current Type");
        }

        return dt;
    }

The error I get when I try to run it is the following: Array size cannot be specified in a variable declaration

Upvotes: 0

Views: 58

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23218

You should change this declaration

dt.Columns.Add(info[i].Name, typeof(info[i].GetType()); 

to the following

dt.Columns.Add(info[i].Name, info[i].FieldType); 

Add method accepts string as column name and Type as column type, obviously. FieldType property contains the type of object which this field belongs to

Upvotes: 3

Related Questions