Blazor @Code and Code-Behind Files for Using C# Code With Razor Pages
A quick primer on the subject!
When working with Blazor, you are probably aware of the fact that you can write C# code directly into your Razor page files but there are rules for where to store this, as explained below.
Where to Put Code in Razor Pages within Blazor Projects
When using C# code to be used directly with a Razor page and its contents, this code can be stored in two places:
Code Block
In a code block at the bottom of the file
Denoted by @code directive followed by curly brackets at the bottom of the file
For example:
@code {
public int MyProperty { get; set; }
}This just needs to be in the same file and by convention, rather than rule, it comes at the bottom of the file.
However, from working in a team with a fairly large Blazor project, we never use this option. It seems more relevant for small-scale testing or initial development. The preferred option is the code-behind file, as will be explained below.
Code-Behind File
The preferred place to store C# code to be run in Razor pages within a Blazor project is within a code-behind file.
This is so-called since it essentially creates a link to the Razor page by way of naming and is therefore paired with that file, placed below the Razor page file in the hierarcy.
The file extension conventions are as follow for Razor pages and their corresponding code-behind files:
Razor page/file: MyRazorFile.razor
Code-behind file: MyRazorFile.razor.cs
They also sit in that order with the razor.cs file indented below the .razor file as with a hierarchical parent-child relationship, so visually they are clearly connected as well as by name.
The razor.cs file just becomes a C# class, so that part is straightforward, although you will need to use the [Parameter] and [Inject] decorators for any properties to be used in ways their names indicate, i.e. for passing parameters to the Razor page or for using injected dependencies from elsewhere within your project.
Summary
So, in summary, you can store your C# code to be used in a Razor page in the following ways
In a code block at the end of your Razor file
Use the @code directive to start this, following immediately by curly brackets and place your code within it.
In a “code-behind” file that shares the same name as the .razor file but with the .cs file extension after it.
Most IDEs will let you extract any existing code into a code-behind file, so you don’t have to worry about getting the naming exactly right. You can do this in Visual Studio 2022 (VS2022), for instance, by right clicking on the code block to reveal the extract to code-behind file option.

