C# – Using reflection to get properties from subclass and base class

I came across this scenario recently where I needed to use reflection to get the properties declared in a subclass, and then get the properties declared in the base class. I had to handle these sets of properties differently.

Here’s an example. Consider the following two classes. PersonBase is the base class. Driver is the subclass.

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)

To only get the subclass properties, use BindingFlags.DeclaredOnly (which causes it to exclude inherited properties):

using System.Reflection; var props = typeof(Driver).GetProperties( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); foreach (var prop in props) { Console.WriteLine(prop.Name); }
Code language: C# (cs)

Note: Use GetType() instead of typeof() if you’re working with an object.

This outputs the subclass properties:

MilesDriven CanDriveManual
Code language: plaintext (plaintext)

To get the base class properties, use BaseType to get the base class’s type info, and then get its properties:

using System.Reflection; var props = typeof(Driver).BaseType.GetProperties(); foreach (var prop in props) { Console.WriteLine(prop.Name); }
Code language: C# (cs)

Note: Of course, if you know what the base class is ahead of time, you could just call typeof() on the base class. However, chances are you won’t want to hardcode this.

This outputs the base class properties:

FirstName LastName Id
Code language: plaintext (plaintext)

In a generic method

It’s common to need to use reflection with generic methods. So here’s an example of getting subclass and base class properties in a generic method:

using System.Reflection; string GenerateColumnCSV<T>() where T : PersonBase, new() { var subclassProps = typeof(T).GetProperties( BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); var baseclassProps = typeof(T).BaseType.GetProperties(); //use the properties. For example, generate column lists var subclassPropNames = subclassProps.Select(p => $"sub.{p.Name}"); var baseclassPropNames = baseclassProps.Select(p => $"base.{p.Name}"); return String.Join(", ", baseclassPropNames.Concat(subclassPropNames)); }
Code language: C# (cs)

Call the generic method:

Code language: C# (cs)

This outputs the following:

base.FirstName, base.LastName, base.Id, sub.MilesDriven, sub.CanDriveManual
Code language: plaintext (plaintext)

Leave a Comment