public/internal/protected/private (with note on file)
Learn how public, internal, protected, and private change visibility; see inheritance and same-assembly rules. Note that file-scoped access is not in C# 6.
Access modifiers overview
Goal: Pick the right visibility.
- public: anywhere
- internal: same assembly
- protected: derived classes
- private: same class
- file: newer than C# 6 (info only)
private vs public
Keep fields private and expose validated public members.
using System;
// private: only inside the class; public: everywhere the class is visible
public class Box
{
private int _width; // hidden storage
public int Width // controlled access
{
get { return _width; }
set { _width = value < 0 ? 0 : value; } // simple guard
}
}
public class Program
{
public static void Main(string[] args)
{
Box b = new Box();
// b._width = -5; // INVALID: private (kept as comment)
b.Width = 10; // OK: public property
Console.WriteLine("Width = " + b.Width);
}
}
All lessons in this course
- public/internal/protected/private (with note on file)
- Namespaces, using directives, global usings (note)
- Partial types & files