- Use
varonly when the type is obvious; otherwise, use explicit types. - Keep line length under 120 characters.
- Use consistent indentation and always include braces (
{}) even for single-line statements. - Group
usingdirectives withSystem.*first, then others in alphabetical order.
- Use
PascalCasefor component names, classes, methods, and properties. - Use
camelCasefor parameters and local variables. - Prefix private fields with
_(e.g.,_userService). - Blazor component files must match the component class name (e.g.,
MyComponent.razormust containMyComponent).
- Split large components into smaller, reusable child components.
- Use
@code { }instead of@functions { }. - Keep UI markup and C# logic separate when complexity grows (e.g., use partial classes).
- Avoid directly mutating bound parameters (
[Parameter]) in child components. - Use
EventCallback<T>instead ofActionor custom delegates for parameter events. - Use
CascadingParameterfor passing data like authentication state, theme, or culture. - Prefer
OnInitializedAsync()overOnInitialized()when usingawait.
- Organize components by domain/feature in folders (e.g.,
Pages/,Components/,Shared/). - Follow the MVU or MVVM pattern when the state becomes complex.
- Use
@injectfor dependency injection rather than service locators. - Prefer
RenderFragmentoverMarkupStringunless you need raw HTML rendering.
- Minimize re-rendering by using
ShouldRender()or conditional UI logic. - Use
@keyin@foreachloops to help Blazor track DOM elements. - Avoid using
async void; useasync Taskinstead. - Dispose components that use resources by implementing
IDisposable.
- Never trust client-side validation—always validate on the server.
- Avoid exposing sensitive logic or secrets in
.razorfiles. - Use
Microsoft.AspNetCore.Components.Authorizationfor secure user authentication and role checking. - Use proper encoding when injecting raw HTML or third-party content.
- Prefer
RenderFragmentparameters to allow child content injection (similar to slot in other frameworks). - Isolate reusable logic in services or base classes.
- Use feature-based folders to group pages, components, and services.
- Use
bUnitfor unit testing Blazor components. - Mock services using
Moq,FakeItEasy, orNSubstitutein test projects. - Use
IJSRuntimeabstraction for JavaScript interop, and mock it in tests. - Validate components for accessibility (ARIA, keyboard navigation).
- Use
@refcautiously to avoid tight coupling. - Enable detailed error messages in development mode.
- Use browser dev tools and Blazor’s built-in error boundaries.
- Follow the Arrange-Act-Assert pattern in unit tests.
- Ensure all services are injected through interfaces.
- Avoid static classes unless stateless and pure utility.
- Keep logic out of the UI layer when possible for easier testing.