Is it possible to use the name `class` as a Blazor component’s parameter name?

I would like to be able to use the parameter name class for a Blazor component:

<MyComponent class="my-css-class" />

I tried to implement it like this:

<div class="@class">
</div>

@code {
    [Parameter]
    public string? class { get; set; }
}

However, since class is a reserved keyword in C#, it makes the IDE and compiler confused:

enter image description here

Is it possible somehow to use class as a parameter name?

If you truly wanted to use class as a property name instead of Class, then you could escape the reserved keyword in the usual way by prefixing it with an @, and then wrap any references to it in the razor with parentheses.

<div class="@(@class)">
</div>

@code {
    [Parameter]
    public string? @class { get; set; }
}

Personally I would just go with C# naming conventions though:

<div class="@Class">
</div>

@code {
    [Parameter]
    public string? Class { get; set; }
}

A solution is to add a parameter in the Razor component that captures unmatched values:

[Parameter(CaptureUnmatchedValues = true)]
public IReadOnlyDictionary<string, object>? Attributes { get; set; }

It is possible to get and use the class parameter in the Razor component by rewriting it like this:

<div class="@CssClass">
</div>

@code {
    [Parameter(CaptureUnmatchedValues = true)]
    public IReadOnlyDictionary<string, object>? Attributes { get; set; }

    string CssClass
    {
        get
        {
            if (Attributes != null &&
                Attributes.TryGetValue("class", out var @class) &&
                Convert.ToString(@class) is { } classString &&
                !string.IsNullOrEmpty(classString))
            {
                return classString;
            }
            return "";
        }
    }
}

Then, you may use the Razor component and set its class parameter:

<MyComponent class="my-css-class" />

Leave a Comment