Type’s class GetProperties method returns us with a array of PropertyInfo objects. Similarly GetProperty method provided with a name of Property returns us a PropertyInfo object. It allows us to access a lot of information and interaction concerning specific property, such as:
Does property have get or set accessor,
Properties Attributes,
Name,
Return type,
Allows us to change it’s value.
And so on…
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 84 85 86 87 88 89 90 91 92 |
using System; using System.Reflection; namespace ReflectionTutorial { class Program { static void Main(string[] args) { Employee emp1 = new Employee(100, "Mark", 28, 2, 2000); Type type = Type.GetType("ReflectionTutorial.Employee"); //Type type = typeof(Employee); //Type type = emp1.GetType(); PropertyInfo propertyInfo = type.GetProperty("YearsEmployed"); // Returns property name string singlePropertyName = propertyInfo.Name; // Does property have get accessor bool GetExists = propertyInfo.CanRead; // Does property have set accessor bool SetExists = propertyInfo.CanWrite; // Type of a property var returnTypeOfProperty = propertyInfo.PropertyType; // To change properties value we use SetValue // that expects minimum of 2 parameters. // First parameter should be the object whose property value will be set // in our case that is instance of a Employee class. // If you desire to change static field use null value for first parameter. // Second parameter should be the value itself propertyInfo.SetValue(emp1, 34); Console.WriteLine("YearsEmployed: {0}", emp1.YearsEmployed); // If property has get and set accessors we should see two methods // Note that GetAccessor method returns MethodInfo[] array MethodInfo[] propertyMethods = propertyInfo.GetAccessors(); // GetProperties method returns us with PropertyInfo_ array // so we can itterate through multiple properties at the same time. PropertyInfo[] propertyInfoArray = type.GetProperties(); foreach (PropertyInfo property in propertyInfoArray) { Console.WriteLine(property.Name + " " + property.GetValue(emp1)); } Console.ReadKey(); } } 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 SallaryIncreaseCoeficient(double coeficient) { return coeficient * YearsEmployed; } } } |
Next time we will continue with MethodInfo class.
Leave a Reply