There are multiple ways to create a Blazor component, but the most common one is to create a .razor file. A razor file can contain a mix of Razor markup, C#, and HTML.
Razor
<p>@username</p>
@code {
string username;
protected override void OnInitialized() => username = "meziantou";
}
Some components may require a lot of HTML and C# code, making the file long and harder to maintain. Also, Visual Studio tooling is not as strong when editing .razor files compared to .cs files. Note that this is something Microsoft is working on. In some cases, it can be beneficial to split the markup and C# code into different files. This approach is similar to code-behind in WinForms or WPF.
When you compile a project that contains a .razor file, the .razor files are first compiled to C#. Each razor file is converted to a partial class where the razor markup is used to create the BuildRenderTree method and the @code section is copied as-is. You can see the generated files in the obj folder if you are curious.
Thanks to this compilation step, it is possible to move the @code section into a regular C# file, as long as you use a partial class with the same name and namespace as the one generated by the razor file.
Create a file with the same name as the component

Create a partial class with the same name as the component, and move the code from the razor file into the class
C#
namespace BlazorDemo.Pages
{
public partial class CurrentUser
{
string username;
protected override void OnInitialized() => username = "meziantou";
}
}
Note that you don't need to move all the code from the @code section to the .cs file. You can keep some code in the .razor file and the rest in the .cs file.
#Configuring file nesting
By default, Visual Studio shows the file at the same level in the solution explorer.
Solution 1: Rename the file from Component.cs to Component.razor.cs
Solution 2: Configure Visual Studio to nest files as you want:

Set the following content to put the .cs files under the .razor files:
JSON
{
"help": "https://go.microsoft.com/fwlink/?linkid=866610",
"dependentFileProviders": {
"add": {
"extensionToExtension": {
"add": {
".cs": [
".razor"
]
}
}
}
}
}
Finally, enable the custom settings:

Do you have a question or a suggestion about this post? Contact me!