📓 3.2.4.2 Optional Features of C# Versions 9 and 10
With every new version of C# and .NET, new features are released. That's to be expected! What you may not expect is that we don't cover or use the majority of these features in the LearnHowToProgram.com curriculum. That leaves learning about new features for further exploration for your shared or independent projects.
In this lesson, we're going to cover three more noticeable syntax updates with recent versions of C# that allow us to write less code. We'll also share resources that you can use to peruse more tools.
Note that .NET releases a new version every year, and a new long-term support version every two years, so expect new tools to become available regularly. To learn more about the Microsoft product support and lifecycle for .NET, visit this documentation.
File Scoped Namespaces
Starting in C# version 10, we can write namespaces as a statement instead of nesting a code (classes) within a namespace. For example, this means that we can rewrite our Program.cs to include namespace ToDoList;, as a statement:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace ToDoList;
class Program
{
static void Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
WebApplication app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
app.Run();
}
}
Note that if a file has multiple classes in it, the namespace statement will apply to all classes. This means that we cannot use namespace statements when a single file has multiple namespaces in it.
To learn more visit the Microsoft (MS) Documentation on namespaces in C#.