Create instance from assembly that is in your project References
The following examples create instances of DateTime class from the System assembly.
-
- DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));
-
- DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime), new object[] { 2008, 7, 4 });
Create instance from dynamically loaded assembly
All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.
- namespace Test
- {
- public class Calculator
- {
- public Calculator() { ... }
- private double _number;
- public double Number { get { ... } set { ... } }
- public void Clear() { ... }
- private void DoClear() { ... }
- public double Add(double number) { ... }
- public static double Pi { ... }
- public static double GetPi() { ... }
- }
- }
Examples of using reflection to load the Test.dll assembly, to create instance of the Calculator class and to access its members (public/private, instance/static).
-
- Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");
-
- Type calcType = testAssembly.GetType("Test.Calculator");
-
- object calcInstance = Activator.CreateInstance(calcType);
-
- PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");
-
- double value = (double)numberPropertyInfo.GetValue(calcInstance, null);
-
- numberPropertyInfo.SetValue(calcInstance, 10.0, null);
-
- PropertyInfo piPropertyInfo = calcType.GetProperty("Pi");
-
- double piValue = (double)piPropertyInfo.GetValue(null, null);
-
- calcType.InvokeMember("Clear",
- BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
- null, calcInstance, null);
-
- calcType.InvokeMember("DoClear", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, calcInstance, null);
-
- double value = (double)calcType.InvokeMember("Add", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, calcInstance, new object[] { 20.0 });
-
- double piValue = (double)calcType.InvokeMember("GetPi",
- BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, null);
-
- double value = (double)calcType.InvokeMember("_number",
- BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
- null, calcInstance, null);