Instantiate a Class Dynamically in C#
You can dynamically instantiate a class in C# using reflection, it’s possible to instantiate code from assemblies which are not referenced at build-time. For example, if you had class defined in DynamicInstantiateLb.dll:
public class DynamicTestClass
{
public int Add(int x, int y)
{
return x + y;
}
public string CombineStrings(T x, T y)
{
return x.ToString() + “, “ + y.ToString();
}
}
In a separate assembly which doesn’t a reference to DynamicInstantiateLb.dll, you can still use this code to create an instance of DynamicTestClass:
Assembly assembly = Assembly.LoadFrom(“DynamicInstantiateLb.dll”); Type type = assembly.GetType(“DynamicInstantiateLb.DynamicTestClass”); object obj = Activator.CreateInstance(type);












No comments yet... Be the first to leave a reply!