C# – Get subclass properties with reflection

When you use reflection to get properties, you can get just the subclass properties by using BindingFlags.DeclaredOnly (this causes it to exclude inherited properties). Here’s an example:

using System.Reflection;

var props = typeof(Driver).GetProperties(
	BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);

foreach (var prop in props)
{
	Console.WriteLine(prop.Name);
}

//Base class and subclass below

public abstract class PersonBase
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int Id { get; set; }
}

public class Driver : PersonBase
{
	public decimal MilesDriven { get; set; }
	public bool CanDriveManual { get; set; }
}
Code language: C# (cs)

Note: Use GetType() if you have an object. Use typeof() if you have a class.

The code outputs just the subclass properties (from the Driver subclass):

MilesDriven
CanDriveManualCode language: plaintext (plaintext)

Get base type properties

To get the base class properties, use BaseType to get the base class type, then get its properties. Here’s an example:

using System.Reflection;

var props = typeof(Driver).BaseType.GetProperties();

foreach (var prop in props)
{
	Console.WriteLine(prop.Name);
}

//Base class and subclass below

public abstract class PersonBase
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int Id { get; set; }
}

public class Driver : PersonBase
{
	public decimal MilesDriven { get; set; }
	public bool CanDriveManual { get; set; }
}
Code language: C# (cs)

This outputs just the inherited properties that come from the base class:

FirstName
LastName
IdCode language: plaintext (plaintext)

Leave a Comment