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 … Read more

C# – Using reflection to get properties

You can get a list of a type’s properties using reflection, like this: Note: If you have an object, use movie.GetType().GetProperties() instead. This outputs the following: When you use GetProperties(), it returns a list of PropertyInfo objects. This gives you access the property’s definition (name, type, etc…) and allows you to get and modify its … Read more

System.Text.Json – Using anonymous types to customize serialization

It’s common to need to customize serialization. When you need to do this, you’d typically need to create a custom converter and pass it in during serialization. Depending on your scenario, an alternative approach is to use anonymous types, like this: Basically you select properties from another object and format them as desired, and then … Read more

System.Text.Json – How to serialize non-public properties

By default, System.Text.Json.JsonSerializer only serializes public properties. If you want to serialize non-public properties, you have two options: Create a custom converter and use reflection to get the non-public properties. Use the JsonInclude attribute to enable (de)serialization of public properties with non-public accessors (not the same as non-public properties). In this article, I’ll show examples … Read more

C# – Access modifiers

When you’re using a Queue class, you only need access to the Enqueue() and Dequeue() methods. Everything else is private. You don’t need to know how data is stored or managed internally. That’s encapsulation, and it’s enabled by access modifiers. Access modifiers are used to hide members from other code. In C#, there are four … Read more