How to get only the virtual read-only property of a class using reflection ?

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 257
Suppose we have a class as under

public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public virtual int EmployeeAge { private set; get; } //read-only property
public virtual string EmployeeSalary { set; private get; } //write-only property
}


The intention is to obtain only the virtual read-only property i.e. EmployeeAge. The below is the way to do that

                 typeof(Employee)
.GetProperties()
.Where(p => p.GetMethod.IsVirtual)
.ToList()
.ForEach(i => Console.WriteLine(i.Name));


But since properties are not virtual but their accessors are, henceforth , the "write-only property" i.e. EmployeeSalary won't be selected.For that we need to modify the program as under

                 typeof(Employee)
.GetProperties()
.Where(p => p.GetAccessors()[0].IsVirtual)
.ToList()
.ForEach(i => Console.WriteLine(i.Name));


The IsVirtual property of MethodBase class does the trick.This property Gets a value indicating whether the method is virtual.It returns true if this method is virtual; otherwise, false. It is defined as
public bool IsVirtual { get; }


More Info : https://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isvirtual.aspx

Comments or Responses

Login to post response