How to Get subclass properties with reflection in C#
By Tan Lee Published on Feb 04, 2025 524
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
Implement security headers for an ASP.NET Core
Jun 24, 2025
Structured Data using FoxLearn.JsonLd
Jun 20, 2025
RuangAdmin Template
Nov 13, 2024
Modular Admin Template
Nov 14, 2024