Understanding Access specifiers on Classes in C# - 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

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.

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.

The greatest benefit of using access specifiers is when someone else is using your classes. By clearly specifying, what should and what should not be touched within your objects, you can protect your object internal mechanism and integrity from being misused or damaged.
With bigger classes, if you made everything public, you would also make it harder for the user of your code to work with IntelliSense, which is something that is very handy when you deal with unknown libraries.

I have created one application to understand Access Specifiers.
It will be more easy to understand it with code instead of Theory.
I have added my notes in code, for better guidance.
namespace ConsoleApplication1
{
//A normal public class which contains all different types of access-modifier classes in the assembly named 'ConsoleApplication1'
public class Base
{
public class PublicBase
{
public static void fn_PublicBase()
{
Console.WriteLine("fn_PublicBase");
}
}
private class PrivateBase
{
public static void fn_PrivateBase()
{
Console.WriteLine("fn_PrivateBase");
}
}
protected class ProtectedBase
{
public static void fn_ProtectedBase()
{
Console.WriteLine("fn_ProtectedBase");
}
}
internal class InternalBase
{
public static void fn_InternalBase()
{
Console.WriteLine("fn_InternalBase");
}
}
protected internal class ProInternalBase
{
public static void fn_ProInternalBase()
{
Console.WriteLine("fn_ProInternalBase");
}
}
//TIP 1:This class is inside the same class 'Base' so everything is accessible from above.Hurray!!
class Base_Inside
{
public static void fn_Base_Inside()
{
//All methods are easily accessible.Does not consider a modified indeed.
PublicBase.fn_PublicBase();
PrivateBase.fn_PrivateBase();
ProtectedBase.fn_ProtectedBase();
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
//Different class but inside the same assembly named 'ConsoleApplication1'
public class Base_Sibling : Base
{
//TIP 2:This class is NOT in same class 'Base' but in the same assembly so only protected is NOT accessible rest all are accessible.
public void fn_Base_Sibling()
{
PublicBase.fn_PublicBase();
//PrivateBase.fn_PrivateBase(); //ERROR:Accesibility of 'protected'
ProtectedBase.fn_ProtectedBase(); //protected is accessible because Base_Sibling inherit class 'Base'. you can not access it via Base.ProtectedBase
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
Now to Understand difference between internal, protected internal,
I Have added one for project named with Assembly_1 in same
solution.
I have inherited Base class of ConsoleApplication1 to Derived class of Assembly_1.
namespace Assembly_1
{
//TIP:if it does not inherit class 'ConsoleApplication1.Base' then we can not access any thing beacuse this is different assembly.
//TIP:only INTERNAL is NOT accessible , rest all are accessible from first assembly if it inherits class 'Soul'
public class Derived : ConsoleApplication1.Base
{
public class PublicDerived
{
public static void fn_PublicDerived()
{
PublicBase.fn_PublicBase(); //YES, becuase this is 'public'
//PrivateBase.fn_PrivateBase(); //No, becuase this is 'private'
ProtectedBase.fn_ProtectedBase(); //YES, becuase this is 'protected'
//InternalBase.fn_InternalBase(); //No, becuase this is 'internal'
ProInternalBase.fn_ProInternalBase(); //YES, becuase this is 'protected internal'
}
}
}
}

- Update answer 2019 -
Hi You can find accessibility via below table

Related

How to choose between private and protected access modifier to encapsulate members between base and childs classes?

I am trying on a project to use private values in my internal functions. In past I used only public ones, but I noticed that obfuscation is working much better when using as much as possible private parameters.
My question is regarding Parent/Child classes.
In my main class I define all the parameters as following :
public class MyFatherClass
{
private long id = -1;
public long ID { get { return this.id; } set { this.id = value; } }
...
}
So in all internal functions I access to my private value instead of the public one.
Then in my daughter class I just add parameters specific to the child class.
public class MyChildClass : MyFatherClass
{
private long anotherParameter = -1;
public long AnotherParameter { get { return this.anotherParameter; } set { this.anotherParameter = value; } }
...
}
Just, I see that in my Parent class, I can access to id and ID without problem, but from daughter classes I can only access ID(as id is private).
If I understood correct, I would need to replace all private by protected in my parent lass, so it would solve the problem?
What I don't understand is the code is working even if I leave it so.
Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?
I am now hesitating, may I just add a private id in each child class, or may I set id to protected in my parent class?
Thanks for your explanations.
Edit, just adding a screenshot of my reversed code after obfuscation, so you could understand difference on how are obfuscated private/public methods/fields
Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?
When you call a public method on a class, that method can access private members of that class:
public class Foo
{
public void Bar()
{
Baz();
}
private void Baz()
{
// private method called by public method
}
}
var foo = new Foo();
foo.Bar();
This compiles just fine. Your setter is the same: it's public, so callable from everywhere, even if it accesses private members.
As for making your field (private long id = -1;) protected: yes, that will mean you can access it in derived classes. But whether you want to is another question.
You have declared a public property for a reason. Perhaps you want to do some validation in its setter or getter. If not, if you're just using a property to access a private field, you could just ditch the entire private field and use an auto-implemented property:
public long ID { get; set; } = -1;
Then you can access the property everywhere, from within itself, from derived classes and from code using this class.
See also:
What is the difference between a field and a property?
What are Automatic Properties in C# and what is their purpose?
Here is a short and reduced description of what access modifiers do:
Public : fields (variables) and properties (variables encapsulation) and methods (functions and procedures) are visible and accessible by the class itslef, by its childs and by any other external classes.
Private : members (fields, properties and methods) are visible and accessible only by the class, not by its childs nor by any external class.
Protected : members are visible and accessible by the class and by its childs, but not by others classes.
Internal : members are visible and accessible by the class and by its childs and by any class that is in the same assembly (.exe and .dll), but not by a class from another assembly.
So you should set id to protected in the parent class to use it in the childs.
But here is the rule:
If childs classes can modify id you should set as a protected field, and offer a public property (get) if available for external items.
If childs classes are not allowed to modify it you should set it private and offer :
A propected property with only a getter if external items can't access it.
A public property with only a getter if external items can access it.
Don't repeat a member with the same name else it will hide the parent and can cause polymorphism problems, else you know what you do.
You can read these tutorials to more understand access modifier keywords:
C# Access Modifiers
Access Modifiers (C# Reference)
Here are some readings:
C# Tutorial Level 0
C# Tutorial Level 1
C# Tutorial Level 2
C# Tutorial Level 3
C# Snippets # Techi.io
Beginning Visual C# 2008 Programming
The MyChildClass class which inherits from the MyFatherClass can not access the id field because it's private. To make it accessible, you will need to change the field's access modifier to either:
protected :
////////////////////////////////////
// Dll1.dll
////////////////////////////////////
namespace Dll1
{
public class Base
{
//The field we are attempting to access
protected int a;
}
public sealed class Main : Base
{
public void DoSomething()
{
//Can be done sins Main inherits from Base
base.a = 100;
}
}
public class Invader
{
public int GetA()
{
var main = new Main();
main.DoSomething();
// can not be done sins the field is only accessible by those that inherit from Base
return main.a;
}
}
}
////////////////////////////////////
// Dll2.dll
////////////////////////////////////
namespace Dll2
{
public class ADll2Class : Dll1.Base
{
public int GetA()
{
//Can be done because ADll2Class inherits from Dll1's Base class
return base.a;
}
}
}
private protected :
Same as protected but, in the example above, Dll2's class, ADll2Class, will not be able to access the a field because it would be privately protected, in other words only classes from the same dll as Base which inherit from Base will be able to access a.
or you can set it to
internal :
If the a field in the example above was internal, then, same as private protected, Dll2's class wont be able to access it but, the Invader class in Dll1 will be able to access it sins it's part of the same dll as Base.
Note that, sins you mentioned obfuscation, try as hard as you will, the id field can still be accessed by others in an obfuscated state with the help of reflection, especially sins you provide a public property ID, might as well set everything in your project to internal.

How to define "anonymous namespace" in C#?

In C++, in order to define a symbol that is only accessible within the same file, we say
namespace
{
class my_private_class
{ ... }
}
But can I do the same thing in C#? Or do I have to say
namespace __DO_NOT_USE_OUT_OF_.xxx.cs__
{
public MyPrivateClass
{ ... }
}
using __DO_NOT_USE_OUT_OF_.xxx.cs__;
(assuming this is in a file called xxx.cs)?
The later, of cause, will depend on the other programmer regards it or not.
There's no anonymous namespaces in C#, but you can exploit static classes:
namespace MyNamespace // <- Just a namespace
{
// Anonymous Namespace emulation:
// static class can't have instances and can't be inherited,
// it's abstract and sealed
internal static class InternalClass // or public static class
{
// private class, it's visible within InternalClass only
class my_private_class
{ ... }
}
}
There is no such thing in C#, we have something called access modifiers which manage the visibility of types.
The usage is against a class or method, such as:
internal class MyType
{
}
Or
protected void MyMethod()
{
}
You will have to pick the one that applies to your scenario, here are the details:
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
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.
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

Why protected internal class cannot derive?

Scope of the protected internal is same assembly, or by any derived class in another assembly.Then Why protected internal class cannot derive?
Sample code:
protected internal class AbsClass
{
int m = 50;
public int am = 5;
public void nonAbsfn()
{
Console.WriteLine(m + am);
}
}
class TestAbstract : AbsClass
{
}
A class can only be protected internal if it is an inner class.
Otherwise, a class can only be public or internal.
To fix your compilation error, make the class either public or internal. The error you are getting has nothing to do with the derived class TestAbstract.
According to the MSDN documentation:
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
So you should be able to do it. Can you post some of your code?

Inconsistent accessibility: base class is less accessible than child class

I am reading book "C# 4.0 in a nutshell" by Joseph Albabari and Ben Albabari. From there I find a topic restrictions on access modifiers. Page 91, Topic "Restrictions on Access Modifiers".
Quoting from the book.
The compiler prevents any inconsistent use of access modifiers. For
example, a sub- class itself can be less accessible than a base class,
but not more
So this says that base class should be equally or more accessible than subclass. So if base class is internal then subclass should be either private or internal. If base class is private and sub class is public then compile time error will be generated. While trying this in Visual Studio I found some strange behavior.
Try 1: Base is private and sub class is private (Works, right behavior) This also works if both are internal, public.
private class A { }
private class B : A { } // Works
Try 2: Base is private and sub class is public or internal (This fails, right behavior)
private class A { }
public class B : A { } // Error
Try 3 : Base is internal and sub is public (This works, but it should fail. As Base is less accessible than sub class
internal class A { }
public class B : A { } // Works, but why
Now my question is why Try 3 didn't failed? Sub class is public and is more accessible than base class which is internal. Even the book says this should fail. But Visual Studio compiled this successfully. This should work or not?
Edit:
I created a new Console Project in VS. In Program.cs I added my code. Here is complete code of Program.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication
{
class Program
{
internal class A { }
public class B : A { } // Error
static void Main()
{
}
}
}
You are placing your nested classes within another internal class.
For example, given:
class Program
{
static void Main(string[] args)
{
}
internal class A { }
public class B : A { }
}
It will compile because the internal modifier of the wrapping class makes the public modifier on class B moot. Rather, type B's accessibility is limited by its wrapped class Program -- its accessibility domain is internal as well.
If you update it to be:
class Program
{
static void Main(string[] args)
{
}
}
internal class A { }
public class B : A { }
It will throw the inconsistent visibility compiler error. Or if you redefine Program to be public instead of internal it will also throw the error. In this case, B's accessibility domain is now public and no longer limited by Program's internal accessibility domain.
From the C# specification 3.5.2 Accessibility Domains:
The accessibility domain of a nested member M declared in a type T
within a program P is defined as follows (noting that M itself may
possibly be a type):
If the declared accessibility of M is public, the accessibility domain of M is the accessibility domain of T.
And the MSDN's description of Accessibility Domain:
If the member is nested within another type, its accessibility domain
is determined by both the accessibility level of the member and the
accessibility domain of the immediately containing type.
If the wrapping type Program is internal, then the nested type B being public will have its accessibility to match Program, thus it is treated as internal and no compiler error is thrown.
private inherited classes can not accessible in other classes when you inherit private class with other public class then it contains the reference of private class and its data so it is not possible.
abstract class test
{
public abstract void add();
public int num1;
public string str;
}
class test3 : test1
{
public override void add()
{
throw new NotImplementedException();
}
}
both classes are private.
if you use internal then you can access only in assembly.

How do I specify a method that can be accessed only from derived classes of the same assembly?

Is there any way in C# to specify a method that can be accessed only from derived classes of the same assembly without using internal access modifier?
Thanks.
You have to specify both internal as well as protected.
Give the scope of the class as internal
and method scope as protected
Internal class Myclass
{
Protected void MyMethod()
{
//Do something
}
}
Read about C# Protected Internal
protected A protected member is accessible within its class and by
derived classes.
internal Internal types or members are accessible only within
files in the same assembly.
protected internal Access is limited to the current assembly or
types derived from the containing
class.
* protected internal is the only access modifiers combination allowed
for a member or a type.
So you need to use internal key word after all:
protected internal memberName(){ ... };
I believe you can do something like:
public class OriginalClass { ... }
internal class DerivedClass: OriginalClass
{
protected void MemberName() { ... }
}
This way, only internal classes can see the DerivedClass and only internal derived classes can see the portected members inside it.
And also, you still able to access the OriginalClass from everywhere.
Ok! I imagine the situation where you would like to have more flexible control of what assembly class is from, and what class is derived from, than with 'internal' keyword. For example if you wish to check that the object is from th-a-at assembly and derives from one of the-e-e-ese classes.
You can do it through Assembly.GetAssembly() method of the type
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getassembly.aspx
And here is the way to check if object is derived one from another.
Check if a class is derived from a generic class
So you can check all you need.
Then you can implement something like:
public static bool CheckTypeIsCorrect(Type t)
{
if(t.GetAssembly().FullName != AssemblyYouNeed) return false;
if(!(check anything you want in the class)) return false;
return true;
}
...
public void YourMethod(object value)
{
if(!CheckTypeIsCorrect(typeof(value)))
throw ArgumentException("Type of the object is not correct");
...
}
Make the function Access modifier as Protected in your Base Class. Like below
protected void YourFunctionName()
{
//This will be accessible in your derived class only.
}
A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
Below is an example from MSDN
namespace SameAssembly
{
public class A
{
protected void abc()
{
}
}
private class B : A
{
void F()
{
A a = new A();
B b = new B();
a.abc(); // Error
b.abc(); // OK
}
}
}

Categories