Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Access specifiers on Classes in C#

First of all let me start by saying that I do understand access specifiers I just don't see the point of using them in classes. It makes sense on methods to limit their scope but on classes, why would you want a private class, isn't it the purpose of classes to be able to reuse them?

What is the purpose of access specifiers when declaring a class in C#? When would you use them?

Thanks

like image 807
fs_tigre Avatar asked Dec 14 '22 08:12

fs_tigre


2 Answers

Well, let's say that you want a class to be only accessed inside her own assembly:

internal class Test

Let's say that you have two classes, one inside the other (nested classes):

protected internal class TestA
{
    private TestB _testB;

    private class TestB
    {
    }

    public TestA()
    {
        _testB = new TestB();
    }
}

The TestB class can be only accessed inside methods/properties/contructors inside TestA or inside herself.

The same applies to the protected modifier.

// Note

If you don't specify the access modifier, by default it will be private, so on my example the following line:

private TestB _testB;

is equal to

TestB _testB;

And the same applies to the class.

Special Modifier

Then, there is the protected internal which joins both modifiers so you can only access that class inside the same assembly OR from a class which is derived by this one even if it isn't in the same assembly. Example:

Assembly 1:

public class TestA : TestB
{
    public TestB GetBase()
    {
        return (TestB)this;
    }

    public int GetA1()
    {
        return this.a1;
    }
}
protected internal class TestB
{
    public int a1 = 0;
}

Program

TestA _testA = new TestA(); // OK
TestB _testB = new TestB(); // ERROR

int debugA = new TestA().a1 // ERROR
int debugB = new TestA().GetA1(); // OK

TestB testB_ = new TestA().GetBase(); // ERROR

Source

Link (Access Modifiers)

  • Internal

The type or member can be accessed by any code in the same assembly, but not from another assembly.

  • Private

The type or member can be accessed only by code in the same class or struct.

  • Protected

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

  • Public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

like image 172
Leandro Soares Avatar answered Dec 27 '22 19:12

Leandro Soares


I will give you an example of an internal class. Imagine I have some DLL. Form this DLL I want to expose only a single class called A. This class A however, should have access to other classes inside DLL - thus I will make all other classes inside DLL internal. Hence, from the DLL you can only use class A, while A can still access other classes inside DLL - you however, can't.

like image 21
Giorgi Moniava Avatar answered Dec 27 '22 20:12

Giorgi Moniava