How to Get subclass properties with reflection in C#
By FoxLearn 2/4/2025 4:31:27 AM 64
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
- Primitive types in C#
- Connection string password with special characters in C#
- Ignoring Namespaces in XML when Deserializing in C#
- How to Change the Cursor to a Wait Cursor in C#
- Enum Generic Type Constraint in C#
- Capturing screenshots in C#
- ChromeDevToolsSystemMenu does not exist in the current context in CefSharp
- How to download a webfile in C#
Categories
Popular Posts
Material Admin Dashboard Template
11/15/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024
SB Admin Template
11/17/2024