Skip to content

C# classes, constructors and access modifiers

This is the third page of the C# basics path. So far the samples have used built-in types and a few static helper methods. Real programs model their own concepts: an OrdersPortal shop has products, customers, carts and orders, each with data and rules. This page shows how to write those types as classes, how constructors make sure every object starts in a valid state, how access modifiers protect that state, and when a member should belong to the class itself rather than to each object.

You will finish with a shopping cart made of three classes: Product, CartLine and Cart. Products are immutable once created, the cart validates every quantity, repeated products merge into one line, outside code cannot change the cart’s lines directly, and a static counter numbers each cart. Each section adds one idea and ends with output you can compare against your own run.

  • The .NET 10 SDK or later. The samples were compiled and run with .NET SDK 10.0.115 (C# 14). The final program uses ArgumentOutOfRangeException.ThrowIfLessThan, which needs .NET 8 or later.
  • A console project (dotnet new console -o OrdersPortal.Basics). Replace Program.cs with each sample and run dotnet run. Type declarations go after the top-level statements in the same file; in a real project you would give each class its own file.
  • The previous pages: types, variables and operators and control flow and methods.

A class is a blueprint: it declares the data each object holds and the operations it supports. An object (or instance) is one concrete value built from that blueprint with new. Every object has its own copy of the instance data, while all objects share the same method code.

Data usually lives in properties. public string Sku { get; set; } is an auto-implemented property: the compiler creates a hidden field and the get and set accessors that read and write it. A property looks like a field to callers but can later gain validation or computed logic without breaking them, which is why public data in C# is almost always a property rather than a public field. The object initializer new Product { Sku = "...", Price = 89.00m } sets properties right after construction.

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var first = new Product(); // new creates an object (an instance) from the class
first.Sku = "CABLE-01";
first.Name = "USB-C cable";
first.Price = 9.99m;
var second = new Product { Sku = "DOCK-03", Name = "Laptop dock", Price = 89.00m }; // object initializer
Console.WriteLine(first.Describe());
Console.WriteLine(second.Describe());
Console.WriteLine(first.PriceWithVat(0.20m));
Product alias = first; // copies the reference, not the object
alias.Price = 7.49m;
Console.WriteLine($"first.Price is now {first.Price}");
Console.WriteLine(ReferenceEquals(first, alias));
var copy = new Product { Sku = first.Sku, Name = first.Name, Price = first.Price };
Console.WriteLine(first == copy); // == compares references for classes by default
// A class groups data (fields and properties) with behavior (methods)
public class Product
{
public string Sku { get; set; } = ""; // auto-implemented property with a default
public string Name { get; set; } = "";
public decimal Price { get; set; }
public string Describe() => $"{Sku}: {Name} at {Price}";
public decimal PriceWithVat(decimal vatRate) => Math.Round(Price * (1 + vatRate), 2);
}

Output:

CABLE-01: USB-C cable at 9.99
DOCK-03: Laptop dock at 89.00
11.99
first.Price is now 7.49
True
False

The second half of the sample matters most. A class is a reference type, so Product alias = first; copies the reference: both variables now point at one object, and changing the price through alias changes what first sees. ReferenceEquals confirms it. The reverse also holds: copy has identical data but is a different object, so == returns False, because for classes == compares references unless the class defines otherwise. When you want types that compare by their data, use a record, covered in the types and records hub.

This class has a weakness: anyone can create a Product with no SKU, or set a negative price later. The next two sections fix both.

A constructor is a special method that runs when new creates an object. It has the class’s name and no return type, and its job is to put the object into a valid state. If you write no constructor at all, the compiler supplies a public parameterless one. As soon as you write any constructor, that free one disappears, so new Customer() only compiles if you declare a parameterless constructor yourself.

A class can have several constructors with different parameter lists. To avoid repeating validation, the shorter ones chain to the most complete one with : this(...), which runs first. A constructor can also call a base class constructor with : base(...), covered on the next page.

Properties with only get can be assigned in a constructor and never again, and the readonly modifier does the same for fields. Together they make objects that cannot drift into an invalid state after construction.

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var standard = new Customer("C-100", "Ana Lopez");
var vip = new Customer("C-200", "Ben Okafor", CustomerTier.Gold);
var guest = new Customer();
Console.WriteLine(standard);
Console.WriteLine(vip);
Console.WriteLine(guest);
try
{
var broken = new Customer("", "No Id");
}
catch (ArgumentException ex)
{
Console.WriteLine($"Rejected: {ex.Message}");
}
public enum CustomerTier { Standard, Silver, Gold }
public class Customer
{
private readonly DateOnly _createdOn; // readonly: assigned only here or in a constructor
// The main constructor validates and sets everything
public Customer(string id, string name, CustomerTier tier)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentException("A customer needs an id.", nameof(id));
}
Id = id;
Name = name;
Tier = tier;
_createdOn = new DateOnly(2026, 11, 18);
}
// Overloads chain to the main constructor with this(...)
public Customer(string id, string name) : this(id, name, CustomerTier.Standard) { }
public Customer() : this("GUEST", "Guest shopper") { }
public string Id { get; } // get-only: set in the constructor, never again
public string Name { get; }
public CustomerTier Tier { get; }
public override string ToString() => $"{Id} {Name} ({Tier}, since {_createdOn:yyyy-MM-dd})";
}

Output:

C-100 Ana Lopez (Standard, since 2026-11-18)
C-200 Ben Okafor (Gold, since 2026-11-18)
GUEST Guest shopper (Standard, since 2026-11-18)
Rejected: A customer needs an id. (Parameter 'id')

Throwing from a constructor is the right response to invalid arguments: the caller never receives a half-built object. nameof(id) puts the parameter name into the exception without a hard-coded string, so renaming the parameter keeps the message correct. The enum declares a small set of named constants, which is clearer than passing magic numbers or strings for a customer tier.

C# offers shorter ways to declare constructors as well. Primary constructors (C# 12) put the parameters on the class declaration itself, and required properties (C# 11) force callers to set them in an object initializer. Learn the classic form first; the object construction and initialization hub covers the newer syntax and when each fits.

Access modifiers decide which code can see a type or member. They are how a class keeps its rules enforceable: if outside code can write a field directly, no validation in your methods can protect it.

Modifier Accessible from
public Any code.
private Only the containing type. The default for class and struct members.
protected The containing class and classes derived from it.
internal Any code in the same assembly (project). The default for top-level types.
protected internal The same assembly, or derived classes in any assembly.
private protected Derived classes in the same assembly only (C# 7.2 and later).

A common pattern is a private field with a public read-only property, or a property with a private set. Callers can read the value but must go through methods that enforce the rules to change it.

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var account = new GiftCard("GC-1");
account.TopUp(50m);
account.Redeem(20m);
Console.WriteLine($"Balance: {account.Balance}");
// account.Balance = 1000m; // CS0272: the set accessor is private
// account._balance = 1000m; // CS0122: '_balance' is inaccessible due to its protection level
var promo = new PromoGiftCard("GC-2", bonusRate: 0.10m);
promo.TopUp(50m);
Console.WriteLine($"Promo balance: {promo.Balance}, history: {promo.HistoryCount} entries");
try
{
account.Redeem(500m);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
public class GiftCard
{
private decimal _balance; // private: only code inside GiftCard
private readonly List<string> _history = new();
public GiftCard(string code) => Code = code;
public string Code { get; } // public: any code
public decimal Balance => _balance; // read-only from outside
internal int HistoryCount => _history.Count; // internal: any code in this assembly (project)
public void TopUp(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
_balance += amount + Bonus(amount);
Record($"top-up {amount}");
}
public void Redeem(decimal amount)
{
if (amount > _balance) throw new InvalidOperationException($"{Code}: only {_balance} left");
_balance -= amount;
Record($"redeem {amount}");
}
protected virtual decimal Bonus(decimal amount) => 0m; // protected: this class and derived classes
private protected void Record(string entry) => _history.Add(entry); // derived classes in this assembly only
}
public class PromoGiftCard : GiftCard
{
private readonly decimal _bonusRate;
public PromoGiftCard(string code, decimal bonusRate) : base(code) => _bonusRate = bonusRate;
protected override decimal Bonus(decimal amount)
{
Record("bonus applied"); // allowed: private protected, same assembly
return amount * _bonusRate;
}
}

Output:

Balance: 30
Promo balance: 55.00, history: 2 entries
GC-1: only 30 left

The commented-out lines show what the compiler stops: setting Balance from outside gives CS0272 and touching _balance gives CS0122. PromoGiftCard derives from GiftCard, so it may override the protected Bonus method and call the private protected Record method, but it still cannot touch the private _balance field. The next page explains virtual, override and base.

Start every member as private and widen access only when another type genuinely needs it. A public member is a promise to every caller; narrowing it later is a breaking change.

A static member belongs to the class itself, not to any object. There is exactly one copy of a static field, shared by every instance, and it exists even before any instance is created. You reach static members through the class name, as in Order.CreatedCount or Math.Round. A static class can contain only static members and can never be instantiated; it suits groups of helper methods such as Money below.

Static methods have no this, so they cannot read instance fields or properties directly; they work only with their parameters and other static members. A static factory method such as Order.Create is a common use: with a private constructor, it becomes the only way to create an order, so it can assign numbers in one place.

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine($"Orders created so far: {Order.CreatedCount}");
var a = Order.Create("C-100");
var b = Order.Create("C-200");
var c = Order.Create("C-100");
Console.WriteLine($"{a.Number}, {b.Number}, {c.Number}");
Console.WriteLine($"Orders created so far: {Order.CreatedCount}");
Console.WriteLine(Money.ToCents(12.34m));
Console.WriteLine(Money.FromCents(995));
public class Order
{
private static int s_nextNumber = 1000; // one copy, shared by every Order
private Order(string number, string customerId) // private: callers must use Create
{
Number = number;
CustomerId = customerId;
}
public static int CreatedCount { get; private set; }
public string Number { get; } // instance members: one per object
public string CustomerId { get; }
public static Order Create(string customerId) // static factory method
{
CreatedCount++;
return new Order($"ORD-{s_nextNumber++}", customerId);
}
}
public static class Money // static class: cannot be instantiated
{
public static long ToCents(decimal amount) => (long)(amount * 100);
public static decimal FromCents(long cents) => cents / 100m;
}

Output:

Orders created so far: 0
ORD-1000, ORD-1001, ORD-1002
Orders created so far: 3
1234
9.95

Static state is shared by the whole program, which is both its use and its risk. A static counter like s_nextNumber is fine in a single-threaded console app, but in a web application many requests run at once, and two of them could read the same value; use Interlocked.Increment or a database sequence there. Static mutable state also makes unit tests depend on the order they run in. Prefer static members for constants, pure helper methods and factories, and keep changing state in objects.

The cart below uses everything on this page: constructors that validate (Product), an internal constructor and internal set so only code in this project can build and adjust lines (CartLine), a private list exposed as IReadOnlyList<CartLine> so callers can read but not modify it, a private constructor behind a static factory, and a static counter. _lines.Sum(...) and _lines.Find(...) take a lambda, a short inline function described in the collections and queries hub.

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var cable = new Product("CABLE-01", "USB-C cable", 9.99m);
var dock = new Product("DOCK-03", "Laptop dock", 89.00m);
var cart = Cart.StartFor("C-100");
cart.Add(cable, 3);
cart.Add(dock);
cart.Add(cable, 1); // same product again: quantities merge
foreach (CartLine line in cart.Lines)
{
Console.WriteLine($"{line.Product.Sku,-9} x{line.Quantity} = {line.Total}");
}
Console.WriteLine($"Cart {cart.Id} for {cart.CustomerId}: {cart.Total}");
Console.WriteLine($"Carts started: {Cart.StartedCount}");
try
{
cart.Add(dock, 0);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Rejected: {ex.ParamName} must be at least 1");
}
public class Product
{
public Product(string sku, string name, decimal price)
{
ArgumentOutOfRangeException.ThrowIfNegative(price);
Sku = sku;
Name = name;
Price = price;
}
public string Sku { get; }
public string Name { get; }
public decimal Price { get; }
}
public class CartLine
{
internal CartLine(Product product, int quantity)
{
Product = product;
Quantity = quantity;
}
public Product Product { get; }
public int Quantity { get; internal set; }
public decimal Total => Product.Price * Quantity;
}
public class Cart
{
private static int s_started;
private readonly List<CartLine> _lines = new();
private Cart(string customerId)
{
s_started++;
Id = $"CART-{s_started:000}";
CustomerId = customerId;
}
public static int StartedCount => s_started;
public static Cart StartFor(string customerId) => new(customerId);
public string Id { get; }
public string CustomerId { get; }
public IReadOnlyList<CartLine> Lines => _lines;
public decimal Total => _lines.Sum(line => line.Total);
public void Add(Product product, int quantity = 1)
{
ArgumentOutOfRangeException.ThrowIfLessThan(quantity, 1);
CartLine? existing = _lines.Find(line => line.Product.Sku == product.Sku);
if (existing is null)
{
_lines.Add(new CartLine(product, quantity));
}
else
{
existing.Quantity += quantity;
}
}
}

Output:

CABLE-01 x4 = 39.96
DOCK-03 x1 = 89.00
Cart CART-001 for C-100: 128.96
Carts started: 1
Rejected: quantity must be at least 1

Try writing cart.Lines.Add(...) or new Cart("C-1") in Program.cs: neither compiles, which is exactly the protection the access modifiers were chosen for.

Exact messages from the .NET 10 SDK compiler:

Error Cause Fix
CS7036: There is no argument given that corresponds to the required parameter 'n' of 'P.P(string)' Calling new P() after declaring only a constructor with parameters. Pass the arguments, or declare a parameterless constructor too.
CS0272: The property or indexer 'P.Name' cannot be used in this context because the set accessor is inaccessible Assigning a property whose set is private. Change it through a method of the class, or rethink whether callers should set it.
CS0122: 'P._secret' is inaccessible due to its protection level Using a private or internal member from outside its scope. Use the public API, or widen access deliberately.
CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) Assigning a readonly field in an ordinary method. Assign it in the constructor, or drop readonly if it really must change.
CS0120: An object reference is required for the non-static field, method, or property 'P.Name' A static method reading an instance member. Make the method an instance method, or pass the value in as a parameter.
CS0712: Cannot create an instance of the static class 'M' new on a static class. Call its members through the class name.
  1. After var b = a; where a is a class instance, how many objects exist? One. b holds a copy of the reference, so changes through either variable affect the same object.
  2. You add a constructor with parameters and new Customer() stops compiling. Why? The compiler only supplies a parameterless constructor when the class declares none. Declare one yourself if callers still need it, usually chaining to the main constructor with : this(...).
  3. What is the default accessibility of a class member with no modifier, and of a top-level class? Members default to private; top-level types default to internal.
  4. Why expose a private field through a property instead of making the field public? The property gives the class one place to validate, compute or log, and lets you change the implementation later without breaking callers. A public field accepts any value from anyone.
  5. When is a static member the wrong choice? When the data belongs to one object, or when it is mutable state shared across threads or tests. Shared mutable statics cause race conditions in web apps and order-dependent tests.

Continue with inheritance and interfaces, which builds families of related classes, defines contracts with interfaces and shows how polymorphism picks the right method at run time.