I am just started to learn Blazor and created a sample blazor application in VS .
Looking at the generated code, I noted that file program.cs is not a class or method, as it contains the following code:
using BlazingPizza.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
// Register the pizzas service
builder.Services.AddSingleton<PizzaService>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<PizzaStoreContext>();
if (db.Database.EnsureCreated())
{
SeedData.Initialize(db);
}
}
app.Run();
The code in this file seems more like a script than a class, method or similar construct in C#.
What is the format of this file? Where is the main function and how the main function related to this code/file?
>Solution :
It’s a new feature in C# 9, called top-level statements.
You can basically have one .cs file per project with top-level statements, that replaces the main method.