7

Introducing C# 10: File-scoped namespaces

 2 years ago
source link: https://anthonygiretti.com/2021/08/12/introducing-c-10-file-scoped-namespaces/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Introducing C# 10: File-scoped namespaces

2021-08-12 by anthonygiretti

Introduction

C# is still evolving and C# 10 proposes a new feature : file_scoped namespaces. As its name suggests, the namespace declared in a file (without braces, but whose instruction ends with a semicolon) will apply to all elements declared in the same file. It’s practical, no more need for indentation since the opening and closing braces of the namespace disappear. There is still a limitation, only one namespace can be declared in the file, otherwise you will get a compiler error.

Example

The following code shows what is a file-scoped namespace:

namespace DemoCsharp10.Products;

public record struct Product { public string Name { get; init; } public int CategoryId { get; init; } public ProductWarranty Warranty { get; init; } }

public enum ProductWarranty { Unlimited = 0, OneYear = 1, TwoYears = 2 }

The following below is illegal:

namespace DemoCsharp10;

namespace Products //Error CS8955 Source file can not contain both file-scoped and normal namespace declarations. { public record struct Product { public string Name { get; init; } public int CategoryId { get; init; } public ProductWarranty Warranty { get; init; } }

public enum ProductWarranty { Unlimited = 0, OneYear = 1, TwoYears = 2 } }

The compiler will throw the following error:

Error CS8955 Source file can not contain both file-scoped and normal namespace declarations.

The following below is also illegal:

namespace DemoCsharp10; namespace Products; //Error CS8954 Source file can only contain one file-scoped namespace declaration.

public record struct Product { public string Name { get; init; } public int CategoryId { get; init; } public ProductWarranty Warranty { get; init; } }

public enum ProductWarranty { Unlimited = 0, OneYear = 1, TwoYears = 2 }

The compiler will throw the following error:

Error CS8954 Source file can only contain one file-scoped namespace declaration.

Like this:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK