In this tutorial we will cover everything related to access modifiers.
Index
1 - What is an access modifier
An access modifier is a code clause that indicates whether you can access a specific code block from another part of the program.
There is a wide variety of access modifiers, and they can be applied to methods, properties, or classes.
2 - Access modifiers
public
Unrestricted access that allows its members to be accessed from anywhere in the code where it is referenced.
public class EjemploPublic
{
public string PruebaAcceso { get; set; }
}
class Program
{
static void Main(string[] args)
{
EjemploPublic ejemplo = new EjemploPublic();
Console.WriteLine(ejemplo.PruebaAcceso); //Funciona correctamente
}
}
Private
Allows access to members exclusively from the class or struct that contains them.
public class EjemploPrivate
{
private string PruebaAcceso { get; set; }
public EjemploPrivate(){
PruebaAcceso = "funciona";//Funciona
}
}
class Program
{
static void Main(string[] args)
{
EjemploPrivate ejemplo = new EjemploPrivate();
Console.WriteLine(ejemplo.PruebaAcceso); //Da un error
}
}
internal
Allows access from within the same project or assembly, but not from an external one.
For example, if you have a library, you will be able to access internal elements from within the same library, but if you reference that library from another project, you won’t be able to access them.
//Libreria externa (Distinto proyecto|Asembly)
public class EjemploInternalLibreria
{
internal string PruebaAcceso { get; set; }
}
class EjemploImprimirInternal
{
public void Imprimir()
{
EjemploInternalLibreria ejemplo = new EjemploInternalLibreria();
Console.WriteLine(ejemplo.PruebaAcceso); //Funciona
}
}
//proyecto principal
class Program
{
void Imprimir()
{
EjemploInternalLibreria ejemplo = new EjemploInternalLibreria();
Console.WriteLine(ejemplo.PruebaAcceso); // Error. Al estar en otro proyecto
}
}
protected
We can access the elements from the same class, or from one that inherits from it.
class EjemploProtected
{
protected string PruebaAcceso { get; set; }
}
class claseHerencia : EjemploProtected //Herencia, osea clase hija.
{
void Imprimir()
{
Console.WriteLine(PruebaAcceso); //Accedemos sin problemas ya que es una propiedad de la clase padre.
}
}
class Program
{
void Print()
{
EjemploProtected ejemplo = new EjemploProtected();
Console.WriteLine(ejemplo.PruebaAcceso); // Error. no podemos acceder ya que esta clase no hereda de EjemploProtected
}
}
protected internal
Combines both protected and internal, allowing access from the same project or assembly or from the types that derive from it.
private protected
Finally, we combine private and protected, which allows access from the current class or from those that derive from it. This allows you to reference methods and properties in classes from which you inherit.
If there is any problem you can add a comment bellow or contact me in the website's contact form