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.
As an example class, we’ll just take my library’s settings
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:
- Create an instance of the class in order to be able to get the default values.
- For each property in the class:
- If the property’s type is a primitive, extract all the needed information (name, type, description and default value)
- 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
Since the documentation of my diagrams library is in Blazor itself, I am using the output of
ExtractPossibleOptions to render a straightforward 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:
- The documentation table reflects the possible options in real time, since the rendering project references the library.
- The table will always be up to date and I save myself the constant “Don’t forget to document this new option” reminders.