Zeb-ur-Rehman
Zeb-ur-Rehman

Reputation: 1209

Convert String Value to User Defined Type

Hi I want to convert string value to DataType so that i can use it. First i would like to describe my question.

1: I have Typed DataSet Named Files
2: This DataSet Contains 6 DataTables
3: DataTables names are (File01, File02, File03, File04, File05, File06)
4: Now i want check dynamically that which DataTable to call and create the instance of that class using Reflection.

string dataTableName = filename + "DataTable"; //This will generate File01DataTable,File02DataTable...,File06DataTable
Type dataTableType = typeof ( Files.File01DataTable ).Assembly.GetType( dataTableName );

5: Now create instance of that DataTable. Here tDS is TypedDataSet Files Instance

dataTableType dt = ( dataTableType )tDS.Tables[filename];

6:But above approch doesn't works. When i try to return the type it returns me null instead of that class. Can someone guide me please.
Thanks in Advance

Edit: Well thanks ronnie Because you solved my 50% of problem. Now When i get type here is the other scenario for instantiating object.

string dataTableName = filename + "DataTable";// It Generate File01DataTable and so on till File06DataTable.

Now When i want to instantiate the object at runtime i cann't tell it

File01DataTable dt = (File01DataTable) tDS.Table[filename];

instead i need generic object it should be decide at runtime which object to instantiate e.g File02DataTable or File05DataTable. So How can i overcome this problem?

Upvotes: 0

Views: 478

Answers (1)

user2024891
user2024891

Reputation:

Is your class nested? If so you will need to add the '+' character between classes. In addition a fully referenced namespace is required to return the type.

namespace SO
{
    class Program
    {
        static void Main(string[] args)
        {
            string dataTableName = "SO.Files+File01DataTable";
            Type dataTableType = typeof(Files.File01DataTable).Assembly.GetType(dataTableName);
            Files.File01DataTable dt = (Files.File01DataTable)Activator.CreateInstance(dataTableType);
        }
    }
}

Upvotes: 1

Related Questions