How to Get subclass properties with reflection in C#
By Tan Lee Published on Feb 04, 2025 261
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
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Implementing Caching in ASP.NET Core
Dec 14, 2024
11 Things You Didn't Know About Cloudflare
Dec 19, 2024