16 November

C# 11 – Files scoped types

Programming

min. read

Reading Time: 2 minutes
C# 11
C# 11

Let’s list all the features that C# 11 brings to the table. Let’s discuss them all one by one, with their use cases, and see how they can come in handy. At the bottom of each article, you can find a link to all 14 new C# features!

Files scoped types

With file-scoped classes or structs, we can create a class that is only visible as part of the current file!

Person1.cs

namespace FileScopedTypes;
public class Person {}

Person2.cs

namespace FileScopedTypes;
public class Person {} // Exception, class FileScopedTypes.Person is already defined

this can be now fixed instead of using public we can define it as file

Person2.cs

namespace FileScopedTypes;
file class Person {}

Note that now, there is no name collision, but also the Person from Person2.cs is not visible outside this file!

This can be very useful to provide an implementation of sorts for some abstract classes, that should not be visible when API visibility is considered. Previously we had to bloat our own namespace with internals, now we can neatly hide this from everyone but us!

public interface IApi
{
    int Const();
}

public class SomeApi : IApi
{
    private FileApi _impl = new();

    public int Const()
    {
        return _impl.Const(); // not visible
    }
}

file class FileApi : IApi
{
    public int Const()
    {
        return 420;
    }
}

Compilation

The file type scope is compiled as {TYPE_NAME}_{UNIQUE_NUMBER} in this way we can never “guess” what the class is but it’s still accessible via reflection when really needed.

Source generators

This feature is mostly here, because source generators needed to generate a name that would not clash with other’s people APIs and types, and now instead of scanning for names, they can just generate “file” as an access modifier.

Further reading at dotnet GitHub page.

Current article:
Files scoped types


Let's talk

SEND THE EMAIL

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.