A personal repository of technical notes. - CSC

How to Create .NET Object From String

Problem
Need to generate an instance of a class dynamically from a string value.

Solution
Use Assembly.CreateInstance Method to create an instance of a type name.
  

Assembly currentAssembly = Assembly.GetExecutingAssembly();

MyClass myClassObjectFromString = null;

try

{

myClassObjectFromString = currentAssembly.CreateInstance("MyNamespace.MyClass") as MyClass;

}

catch

{

}

if (myClassObjectFromString != null)

{

//

}

References
"Assembly.GetExecutingAssembly Method (System.Reflection)." MSDN: Microsoft Development, MSDN Subscriptions, Resources, and More. 23 June 2009 http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly(VS.80).aspx.

"Assembly.CreateInstance Method (String) (System.Reflection)." MSDN: Microsoft Development, MSDN Subscriptions, Resources, and More. 23 June 2009 http://msdn.microsoft.com/en-us/library/dex1ss7c(VS.80).aspx.

See Also
"How to Convert an ASP.NET Control to String |." CSC - Technical Notes. 23 June 2009 http://csc-technicalnotes.blogspot.com/2009/03/how-to-convert-control-to-html-string.html.

No comments:

Post a Comment