Assembly class allows us to:
- Load assemblies
- Explore metadata and types
- Create instance of types
Easiest way to load assembly is by load them using following methods :
GetAssembly (requires Type variable)
GetCallingAssembly (returns Assembly from which this method has been called)
These two methods have Assembly return type. After acquiring Assembly variable we can use it to get types that we want using GetType method.
Let’s explore Assembly class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace ReflectionAssembly { class Program { static void Main(string[] args) { // First we acquire desired assembly Assembly currentAssembly = Assembly.GetEntryAssembly(); // Then a type we want to inspect Type employeeType = currentAssembly.GetType("ReflectionAssembly.Employee"); // Because our Employee class has constructor with parameters // we need to create object array that holds that parameters // that will be used on next line object[] areja = { 100, "Mark", 28, 2, 200.0 }; // To create an instance of a class we use Activator class // and its CreateInstance method // if we do not want to use default parameterless constructor // just do not provide them object employeeInstance = Activator.CreateInstance(employeeType, areja); // nothing new here MethodInfo printEmployeeDetailsMethod = employeeType.GetMethod("PrintEmployeeDetails"); // To call a method just use Invoke method // In this example our method does not have input parameters // so we provide null value // If method needed parameters we would provide object array with parameters printEmployeeDetailsMethod.Invoke(employeeInstance, null); // Just accessing property and retrieving it's return type name PropertyInfo pi = employeeType.GetProperty("Name"); Console.WriteLine(pi.PropertyType.Name); } } public class Employee { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public int YearsEmployed { get; set; } public double Salary { get; set; } public Employee() { Id = -1; Name = "John Doe"; Age = 0; YearsEmployed = 0; Salary = 0.0; } public Employee(int id, string name, int age, int years, double salary) { Id = id; Name = name; Age = age; YearsEmployed = years; Salary = salary; } public void PrintEmployeeDetails() { Console.WriteLine("Employee name: {0}, Age: {1}, Current salary {2}", Name, Age, Salary); } public double SalaryIncreaseCoefficient(double coefficient, string justEmptyParameter) { return coefficient * YearsEmployed; } } } |