jimmy
jimmy

Reputation: 159

In C#, is it possible to restrict a class accessibility to the file defining it?

I can't declare it as private in another class because I have several classes that use it. I also don't want it to be internal otherwise it will be exposed to other classes in the same assembly. I want it to be accessible just to the classes in the same file. Is it possible in C#?

Upvotes: 8

Views: 6433

Answers (2)

It's possible with file access modifier starting from C# 11.

Beginning with C# 11, the file contextual keyword is a type modifier.

The file modifier restricts a top-level type's scope and visibility to the file in which it's declared. The file modifier will generally be applied to types written by a source generator. File-local types provide source generators with a convenient way to avoid name collisions among generated types. The file modifier declares a file-local type, as in this example:

file class HiddenWidget
{
    // implementation
}

Upvotes: 13

Jon Skeet
Jon Skeet

Reputation: 1499870

There's very little in the C# language which is done at at the level of "source file".

The closest you could come would be to create a top-level class and have several nested classes:

class Foo
{
    internal class A
    {
        private Shared shared = new Shared();
    }

    internal class B
    {
        private Shared shared = new Shared();
    }

    private class Shared
    {
    }
}

It's not a very pleasant solution though, to be honest. If a class needs to be visible to a number of other classes, I'd typically prefer to make it internal and either extract out those classes to another assembly or live with the shared class being visible to other clsses in the same assembly which don't really need to know about it.

Upvotes: 13

Related Questions