I need to instantiate an object, and the type of this object will be determined at runtime. The type of the object is pulled from SQL and set to a string value. I also need to pass a number of parameters when creating it. The number / type of parameters will be the same every time (at least for now). What do I need for this, Activator.CreateInstance? Any help would be appreciated.
private void StartScans(int scan_typeid, SqlDataReader drActiveServers)
{
string sql = "SELECT scan_typeclass from scan_types WHERE scan_typeid = " + scan_typeid.ToString();
sqlconn.Open();
SqlCommand cmd = new SqlCommand(sql, sqlconn);
SqlDataReader drScanClass = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string scan_class = drScanClass["scan_typeclass"].ToString();
}
EDIT:
Richard Berg's solution worked in a console application, but not in the above example, I reset scan_class and checked its value, however, I continue to receive this error:
System.ArgumentNullException: value cannot be null. Parameter Name: type
Here my updated code is as follows:
try
{
string sql = "SELECT scan_typeclass from scan_types WHERE scan_typeid = " + scan_typeid.ToString();
sqlconn3.Open();
SqlCommand cmd = new SqlCommand(sql, sqlconn3);
SqlDataReader drScanClass = cmd.ExecuteReader();
drScanClass.Read();
string scan_class = drScanClass["scan_typeclass"].ToString();
var type = Type.GetType(scan_class);
var myObj = Activator.CreateInstance(type, scan_id, scan_name, interval, drActiveServers);
}
catch (Exception e)
{
string sSource = "SharedAuditSVC";
string sLog = "Application";
string sEvent = e.ToString();
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 0);
}
, , , , . ..:)
:
WindowsServiceAudit WSA = new WindowsServiceAudit(scan_id, scan_name, interval, drActiveServers);
:
string scan_class = "WindowsServiceAudit";
var type = Type.GetType(scan_class);
var myObj = Activator.CreateInstance(type, scan_id, scan_name, interval, drActiveServers);