How to Get subclass properties with reflection in C#
By FoxLearn 2/4/2025 4:31:27 AM 81
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
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#