Mark

Mark

  • NA
  • 19
  • 0

Dynamic allocation of Object type

Jun 26 2007 8:41 AM
Dear All,

 

I have a program which can read Data from more than one type of source - i.e. a File or XML feed. I have a listview with a list of sources and the source to retrieve from.

 

Is it possible to assign the type of object created without using an IF statement?

 

Here is some code detail. I have an Interface (IData) which has a method ReadData. Two classes - XMLData and CSVFileData implement this interface.

 

Then in a click button event on my Form I have:

 

Type t = typeof(CSVFileData);

messageQueue = Control.LoadData(t, listViewDataSource.SelectedItems[0].SubItems[1].Text);

 

This sends the Type t, and source path (either filename or url) into the static control class.

 

In the Control.LoadData method I run:

 

object o = Activator.CreateInstance(TypeObj);

//check that it implements the IData Interface

IData dataReader = o as IData;

if (dataReader != null)

{

messages = dataReader.ReadData(Source);

}

 

I have everything in place to do everything dynamically. The only thing that I would like to get rid of is the need to say:

(pseudocode)

 

if (listboxValue="CSV") {

   Type t = typeof(CSVFileData);

} else {

   Type t = typeof(XMLData);

}

 

How can I assign the Type (CSVFileData) more dynamically?

I thought about adding an extra field to the listview to hold the Type, but I'm not sure how you'd convert the string literal to a type.

 

I am very new to C# so I hope the above makes sense. Any help/pointers would be greatly appreciated!


Answers (6)