Extract Available Settings Using C#

I was working these days on my library Blazor.Diagrams and I needed to write some documentation to show all the available/possible options. I could’ve done it manually, but there was quiet a few settings and I didn’t want to have to update the table every time new ones are added.

So I write a quick utility code that generates it for me on the go.

Example class

As an example class, we’ll just take my library’s settings BlazorOptions.

Notice that I used the DescriptionAttribute available in System.ComponentModel to describe each available option. Of course, you can use whatever attribute you want.

Reflection to the rescue

First, we’ll create a class that holds all the information of a single setting:

Here’s what we’re gonna do:

  1. Create an instance of the class in order to be able to get the default values.
  2. For each property in the class:
    1. If the property’s type is a primitive, extract all the needed information (name, type, description and default value)
    2. If the property’s type is a complex object, run step 2 recursively.

We will also need to handle some edge cases for a better output. For example, it would be preferred to turn the type Nullable'1 into Int32?.

Example output

Since the documentation of my diagrams library is in Blazor itself, I am using the output of ExtractPossibleOptions to render a straightforward table:

Blazor.Diagrams' options table

Blazor.Diagrams' options table

As you can see, implementing this method took a couple of minutes and was very easy. Using this, I am sure of two things:

  1. The documentation table reflects the possible options in real time, since the rendering project references the library.
  2. The table will always be up to date and I save myself the constant “Don’t forget to document this new option” reminders.
Zanid Haytam Written by:

Zanid Haytam is an enthusiastic programmer that enjoys coding, reading code, hunting bugs and writing blog posts.

comments powered by Disqus