Introducing C#11: File local types


Have you ever developed/consumed identically named objects and pulled your hair out encapsulating them in different namespaces to avoid compile-time type collisions? Well, C# 11 will make your life easier. Take for example classes that use internally objects that will only be used in a specific context, ie they will not be used in the same assembly or outside of it. C# 11 now allows you to use visible objects inside the same file only and reuse the same type name (class name) in the same assembly without clash! In this post I will show you how to do it.

No more naming collisions

Consider a generic DTO, which materializes a person’s identity as follows:

Now consider that this DTO can be consumed by two different implementations to support the identity of a person, for example, via SQL and HTTP. These two implementations will use a Person object internally which will have the same name, but not the same representation, for example the first with two properties FirstName and LastName while the second will have only one property named FirstNameLastName. As these objects are not used elsewhere than in the SQL or HTTP class which will process a Person object, it then becomes interesting with C# 11 to be able to isolate them in the current file where they are used in order to avoid a naming clash between two Person objects. The keyword, file, which is a modifier type, isolates the Person class in the current file where it is declared:

If you compile your code you won’t get any errors because each Person class is isolated in the file where it is declared. Before C# 11 if you had used the public or internal modifiers you would have had the following error message (for an identical namespace):

Error CS0101 The namespace ‘DemoDotnet7.Mappers’ already contains a definition for ‘Person’

Practical isn’t it ? 😉

Written by


Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: