How to Get subclass properties with reflection in C#
By Tan Lee Published on Feb 04, 2025 431
When you use reflection to get properties, you can retrieve only the subclass's properties by using BindingFlags.DeclaredOnly (which excludes inherited properties).
For example:
using System.Reflection; var props = typeof(Manager).GetProperties( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); foreach (var prop in props) { Console.WriteLine(prop.Name); }
Base class and subclass below:
public abstract class Employee { public string Name { get; set; } public string Department { get; set; } public int EmployeeId { get; set; } } public class Manager : Employee { public int TeamSize { get; set; } public bool HasBudgetControl { get; set; } }
In this case, the code outputs just the properties defined in the subclass (Manager
):
TeamSize HasBudgetControl
Get base type properties
To get the properties of the base class, you can use BaseType
to get the base class type, then fetch its properties.
using System.Reflection; var props = typeof(Manager).BaseType.GetProperties(); foreach (var prop in props) { Console.WriteLine(prop.Name); }
Base class and subclass below:
public abstract class Employee { public string Name { get; set; } public string Department { get; set; } public int EmployeeId { get; set; } } public class Manager : Employee { public int TeamSize { get; set; } public bool HasBudgetControl { get; set; } }
This code outputs the properties inherited from the base class (Employee
):
Name Department EmployeeId
Categories
Popular Posts
Bootstrap 4 Login Page Template
Nov 11, 2024
Responsive Admin Dashboard Template
Nov 11, 2024
RuangAdmin Template
Nov 13, 2024
Gentella Admin Template
Nov 14, 2024