Using Type-Safe Parameters for Cleaner Blazor Components

Often when writing components, one of the parameters may accept more than one value.

For example, suppose we are writing a Modal component and want to allow consumers to declare the size of the modal to suit their needs.

We can define a parameter named Size of type string and have it accept one of four possible values:

  1. Small
  2. Normal (Default)
  3. Large
  4. Extra Large

A part of our Modal.razor file would look like this:

public string Size { get; set; } = "Normal";

Great! Now we can configure the Modal size internally based on the external value supplied through the Size parameter.

But wait, how do consumers know which values are acceptable? Will they have to read documentation elsewhere, or perhaps study the source code of the component? All they know is that it’s a string, and couldn’t they make a big typo anyways?

One way I enjoy solving this problem is through the use of enums. Here’s how:

First, let’s declare an enum inside our Modal.razor component:

public enum SizeValue {

Now let’s change the type of our Size parameter:

public SizeValue Size { get; set; } = SizeValue.Normal;

And that’s all there is to it!

The consumers of our Modal component can now provide the Size parameter very naturally:

<Modal Size="Modal.SizeValue.Large"></Modal>

And internally we can do all of the same operations we were doing with strings but with our special enum type instead.

If we remember that Blazor components are C# classes under the hood, we know we can simply use our own component to access our nested SizeValue enum from elsewhere in our code.

And that’s really what’s going on in here.

This approach has a few benefits that I can think of, namely:

  • Self-documenting and self-validating parameters with IntelliSense code completion.
  • “Type-safe” parameter values that are checked at compile time.
  • Built-in refactoring and reference tracking with Visual Studio.
  • Avoids a whole class of runtime errors by removing loose string checking.
  • Native language support; no need to create an additional class or object.

If these sound appealing, I hope that you will try it and that it’ll help you write cleaner components!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s