C# Tutorials
C# Methods
C# Classes
C# Examples
By now, you're familiar with a public keyword from many of our examples:
public string color;
A public keyword is an access modifier, which is used to set the level of accessibility / visibility of classes, fields, paths and properties.
C# has the following access modifiers:
Modifier | Description |
---|---|
public |
The code is accessible for all classes |
private |
The code is only accessible within the same class |
protected |
The code is accessible within the same class, or in a class that is inherited from that class. You will learn more about inheritance in a later chapter |
internal |
The code is only accessible within its own assembly, but not from another assembly. You will learn more about this in a later chapter |
There's also two combinations: protected internal and private protected.
For now, lets focus on public and private modifiers.
If you are announcing a field with a private access controller, it can only be accessed in the same category:
class Car
{private string model = "Mustang"; static void Main(string[] args)
{Car myObj = new Car(); Console.WriteLine(myObj.model);
}}
If you try to access it outside the classroom, an error will occur:
class Car
{
private string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
When you announce a field with a public access adapter, it is accessible to all classes:
class Car
{
public string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
Note: By default, all class members are private if you do not specify access control:
class Car
{
string model; // private
string year; // private
}