Access modifiers, static and partial
Access modifiers decide who can read or change a member, which is how C# enforces encapsulation. static makes a member belong to the class instead of an object, and partial lets one class live in several files, mostly for generated code.
13.1 The problem: a public field skips the rule
C#
var account = new BankAccount(1000);account.Balance -= 5000;Console.WriteLine(account.Balance); class BankAccount(decimal opening){ public decimal Balance = opening; public bool Withdraw(decimal amount) { if (amount > Balance) return false; Balance -= amount; return true; }}Output
$ dotnet run Bank.cs-4000- The rule is in Withdraw, but the data is public, so anyone with the object can bypass it.
- The bigger the project, the more places the bug can come from; debugging gets hard.
- Fix: data private, changes only through methods = encapsulation.
- Step 1
1.Balance is a public field
- Step 2
2.Outside code does account.Balance -= 5000
- Step 3
3.Withdraw rule is bypassed, balance -4000
- Step 4
4.Fix: public get, private set
- Step 5
5.Bypass now fails at compile time (CS0272)
13.2 Fix: private set
C#
var account = new BankAccount(1000);Console.WriteLine(account.Withdraw(5000));Console.WriteLine(account.Balance); class BankAccount(decimal opening){ public decimal Balance { get; private set; } = opening; public bool Withdraw(decimal amount) { if (amount > Balance) return false; Balance -= amount; return true; }}- Anyone can read Balance; only code inside the class can change it.
- Withdraw(5000) returns False and the balance stays 1000.
- Writing account.Balance -= 5000 again now fails to compile:
Output
# line 2: account.Balance -= 5000;$ dotnet run Bank.cserror CS0272: The property or indexer 'BankAccount.Balance' cannot be used in this context because the set accessor is inaccessibleThe build failed. Fix the build errors and run again.13.3 The 7 access modifiers
| Modifier | Accessible from |
|---|---|
| public | Everywhere |
| private | Same class only |
| protected | Same class + derived (child) classes |
| internal | Anywhere in the same project (assembly) |
| protected internal | Same project OR derived classes |
| private protected | Derived classes inside the same project only |
| file | Same source file only (types) |
- Default for class members: private.
- Default for top-level types: internal.
13.4 internal: the project boundary
- App (console) references the ShopLib class library.
- PriceService is public; GstHelper is internal, an inner helper of the library.
- new GstHelper() in App -> CS0122: for the other project the class simply does not exist.
C#
namespace ShopLib; public class PriceService{ public decimal Final(decimal price) => price + new GstHelper().Tax(price);} internal class GstHelper{ public decimal Tax(decimal price) => price * 0.18m;}Output
$ dotnet run1180.0013.5 Checkpoint: what is the default?
C#
var invoice = new Invoice();Console.WriteLine(invoice.amount); class Invoice{ decimal amount = 500;}Output
$ dotnet run Invoice.csInvoice.cs(2,27): error CS0122: 'Invoice.amount' is inaccessible due to its protection levelThe build failed. Fix the build errors and run again.13.6 static members and static classes
- static member = belongs to the whole class, not to one object; one shared copy.
- Order.Count is incremented by every new Order -> Orders: 2.
- static class (Gst) has no objects: call Gst.Add(1000) directly; new Gst() -> CS0712.
C#
Order a = new(), b = new();Console.WriteLine($"Orders: {Order.Count}");Console.WriteLine(Gst.Add(1000)); class Order{ public static int Count { get; private set; } public Order() => Count++;} static class Gst{ public static decimal Add(decimal price) => price * 1.18m;}Output
# var gst = new Gst();$ dotnet run Shop.cserror CS0712: Cannot create an instance of the static class 'Gst'13.7 partial: one class, many files
- Same class name + partial keyword in each part; the compiler merges them into one class.
- Typical use: one file generated by a tool, your code in the other, so regeneration never deletes your code.
C#
var order = new Order();order.Ship();Console.WriteLine(order.State); // File 1: Order.Generated.cspublic partial class Order{ public string State { get; set; } = "New";} // File 2: Order.cspublic partial class Order{ public void Ship() => State = "Shipped";}Output
$ dotnet run Order.csShipped13.8 partial + source generator
- [GeneratedRegex] with the Indian mobile pattern ^[6-9]\d{9}$.
- static partial Regex Mobile { get; } is only a declaration; the generator writes the body at build time.
- Partial properties since C# 13; C# 14 added partial constructors (and events).
C#
using System.Text.RegularExpressions; string[] numbers = ["9876543210", "12345"];foreach (var n in numbers) Console.WriteLine(Phone.IsValid(n)); static partial class Phone{ [GeneratedRegex(@"^[6-9]\d{9}$")] static partial Regex Mobile { get; } public static bool IsValid(string text) => Mobile.IsMatch(text);}Output
$ dotnet run Phone.csTrueFalse- Step 1
1.You write: static partial Regex Mobile { get; } + [GeneratedRegex]
- Step 2
2.dotnet build runs the Regex source generator
- Step 3
3.Generator emits the other partial part with the implementation
- Step 4
4.Compiler merges both parts into one Phone class
- Step 5
5.Phone.IsValid("9876543210") -> True
13.9 Common mistakes
- Per-user data in a static field: static List<string> items in Cart is shared by Rahul and Priya, so rahul.Count prints 2. In a web app static data is shared across all users and requests. Use an instance field (count 1).
- Thinking private = secure: access modifiers are only compiler rules; reflection can still read private data. Secrets need proper secrets management.
- Making everything public "for now": removing a public member later is a breaking change.
- Using partial to hide a huge class instead of splitting responsibilities.
C#
// Wrong: static -> shared by every cart (prints 2)class Cart{ static List<string> items = []; public void Add(string item) => items.Add(item); public int Count => items.Count;} // Right: instance field -> each cart has its own list (prints 1)class Cart{ List<string> items = []; public void Add(string item) => items.Add(item); public int Count => items.Count;}13.10 5 rules of access
- Fields private; expose properties or methods.
- Start with the least access, widen only when needed.
- Library helpers: internal.
- static only for stateless helpers or truly shared data.
- partial to separate generated code from your code.
13.11 Interview tips
- C# has 7 access modifiers: public, private, protected, internal + protected internal, private protected + file.
- Default: class members private, top-level types internal.
- Encapsulation = private data + public get / private set or methods that enforce rules.
- static class = no instances, only static members (helpers like Math); avoid static for per-user state.
- partial is mainly for generated code (source generators, designers).