WinForms – ComboBox with enum description

By default, when you load enum values into a ComboBox, it’ll show the enum names. If you want to show the enum descriptions (from the [Description] attribute) instead, and still be able to get the selected enum value, you can do the following: I’ll show the code for this below. First, let’s say you have … Read more

C# – Check if a property is an enum with reflection

When you’re using reflection to look at a type’s properties, you can use PropertyInfo.PropertyType.IsEnum to check if the property is an enum. This is helpful when you want to be able to safely call an Enum API method (such as Enum.Parse()) on the reflected type, thus preventing an exception – ArgumentException: Type provided must be … Read more

WinForms – Bind controls to an object data source

Mapping classes to WinForm controls manually is probably the most tedious thing you can do in coding. In order to minimize this coding effort, you can bind your controls to an object data source. In this article, I’ll show how to do this in a WinForms App (.NET Core+) project. First, I’ll show step-by-step how … Read more

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: 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): Get base … Read more

C# – Property order with System.Text.Json

You can use the JsonPropertyOrder attribute to control the order that properties get serialized. You specify the order as an integer, and it serializes the properties in ascending order. Here’s an example: Note: Properties have a default order value of 0. Now serialize an object to JSON: This generates the following JSON: Notice the properties … 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 – 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: In this article, I’ll show examples of both approaches for handling non-public properties. Updated 2022-02-22 to explain the new JsonInclude attribute added in .NET 5. Write a custom JSON converter to serialize non-public properties When the built-in … Read more