How to check if a property is virtual using reflection?

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

public class Employee : IMyInterface
{
public int property1 { get; set; }
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
}

interface IMyInterface
{
int property1 { get; set; }

}


The intention is to obtain only the virtual property of the class.If we apply

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


We will receive the virtual properties of the class along with the Interface property(s)

property1
EmployeeAge
EmployeeSalary

But our intension is to get only the Virtual Properties of the class.So modify the program as under

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

The IsVirtual property of MethodBase class 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

The IsFinal property of MethodBase class gets a value indicating whether this method is final.It returns true if this method is final; otherwise, false. It is defined as

public bool IsFinal { get; }


More Info : https://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isfinal(v=vs.110).aspx

Comments or Responses

Login to post response