As stated above, you can use the Activator class to instantiate the class by its text name.
But there is another option. When you talked about using a similar eval function in C #, I assumed that you would not only want to instantiate the class by its text name, but also populate it with properties from the same line.
For this you need to use deserialization.
Deserialization converts the string as a representation of the class into its instance and restores all its properties that were specified in the string.
Xml serialization. Its using an XML file to convert to an instance. Here is a small example:
public class Report1 { public string Orientation {get;set;} public string ReportParameter1 {get;set;} public string ReportParameter2 {get;set;} }
Above is the class you want to create and populate with parameters with a string. Below is the XML that can do this:
<?xml version="1.0"?> <Report1> <Orientation>Landscape</Orientation> <ReportParameter1>Page1</ReportParameter1> <ReportParameter2>Colorado</ReportParameter2> </Report1>
To create an instance from a file, use System.Xml.Serialization.XmlSerializer:
string xml = @"<?xml version=""1.0""?> <Report1> <Orientation>Landscape</Orientation> <ReportParameter1>Page1</ReportParameter1> <ReportParameter2>Colorado</ReportParameter2> </Report1>"; ///Create stream for serializer and put there our xml MemoryStream str = new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xml)); ///Getting type that we are expecting. We are doing it by passing proper namespace and class name string Type expectingType = Assembly.GetExecutingAssembly().GetType("ConsoleApplication1.Report1"); XmlSerializer ser = new XmlSerializer(expectingType); ///Deserializing the xml into the object object obj = ser.Deserialize(str); ///Now we have our report instance initialized Report1 report = obj as Report1;
This way you can prepare the corresponding xml as a string concatenation. This xml will contain all the parameters for your report.
Then you can convert it to the appropriate type.
source share