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

Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 221
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

.Where(p => p.GetMethod.IsVirtual)
.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

.Where(p => p.GetAccessors()[0].IsVirtual)
.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 :

Comments or Responses

Login to post response