Let's say
class parent
class B : parent
class C : parent
...etc. (may add later......so I don't know how many classes will
there...)
I wanna to let the user type in the class name and instaniate a new
instance e.g.
string userinput = "classB"
parent temp = new SOMEFUNCTION("classB");
I wanted to ask what can SOMEFUNCTION be???
thx!
Use Reflection. Here is a code snippet from the generic ADO.NET project
mentioned in my signature.
===============================================================
private string _targetAssembly; private string _targetName;
private IDbTemplate _target;
private System.Reflection.Assembly _assem;
....
public DbContext(string assembly, string typeName)
{
_targetAssembly = assembly;
_assem = Assembly.LoadFrom(_targetAssembly);
_targetName = typeName;
Type DBType = _assem.GetType(typeName);
if (DBType == null)
{//if typeName did not include namespace...
System.Type[] types = _assem.GetTypes();
for (int i=0; i < types.Length; i++)
{
Type nType = (Type)types.GetValue(i);
if (nType.FullName.IndexOf(typeName) >=0)
{
_targetName = nType.FullName;
DBType = nType;
break;
}
}
}
if (DBType == null)
{
throw new ApplicationException(
"Type name does not exist in specified assembly.");
}
_target = (IDbTemplate)Activator.CreateInstance(DBType);
}
===============================================================
The key lines for you are:
Type DBType = _assem.GetType(typeName);
...
_target = (IDbTemplate)Activator.CreateInstance(DBType);
"IDbTemplate" would be replaced by your parent class or interface name.
If the type is defined in the same assembly as the function shown, then
the "assembly" arguement can be excluded. In that case set the "_assem"
variable with the current assembly.
_assem = Assembly.GetExecutingAssembly();
Let me know if you have further questions.
--
Michael Lang, MCSD
See my .NET open source projects
http://sourceforge.net/projects/colcodegen (simple code generator)
http://sourceforge.net/projects/dbobjecter (database app code generator)
http://sourceforge.net/projects/genadonet ("generic" ADO.NET)