Constructors and object initialisers
Make sure every object starts in a valid state: constructors, overloads, chaining with this(...), initialisers and required members.
Beam and then set its fields one by one. Forget one line and you have a beam with length 0. A constructor is a special method that runs automatically when an object is created, so it can set everything up correctly from the start.
Writing a constructor
public class Beam{ public string Profile; public double Length; // constructor: same name as the class, no return type public Beam(string profile, double length) { Profile = profile; Length = length; }} Beam b = new Beam("IPE300", 6.0); // arguments go to the constructorConsole.WriteLine($"{b.Profile} {b.Length}");IPE300 6
Its name is exactly the class name and it has no return type (not even void).It runs once, when newis used.If you write no constructor, C# gives you an invisible parameterless one. As soon as you write any constructor, that free one disappears.
Overloading and chaining
: this(...). Step through how new runs them:
Validating in the constructor
public Beam(string profile, double length){ if (length <= 0) throw new ArgumentOutOfRangeException(nameof(length), "Length must be positive."); Profile = profile; Length = length;}Object initialisers
var b = new Beam("IPE200", 5.0) { Mark = "B12", Level = 2 }; // with a parameterless constructor you can skip the bracketsvar p = new Point { X = 3, Y = 4 };Primary constructors (C# 12)
public class Beam(string profile, double length){ public string Profile { get; } = profile; public double Length { get; } = length;} var b = new Beam("HEA200", 3.2);required members (C# 11)
public class Column{ public required string Mark { get; init; } public double Height { get; init; } = 3.0;} var c = new Column { Mark = "C1" }; // OK// var d = new Column(); // error CS9035: Mark must be setBankAccount with Owner (string) and Balance (decimal). Add a constructor that requires the owner and an optional opening balance (default 0) that must not be negative (throw ArgumentException otherwise). Create two accounts and print them.
Show the solution
public class BankAccount{ public string Owner; public decimal Balance; public BankAccount(string owner, decimal openingBalance = 0) { if (openingBalance < 0) throw new ArgumentException("Opening balance cannot be negative."); Owner = owner; Balance = openingBalance; }} var a = new BankAccount("Ravi");var b = new BankAccount("Selva", 5000m);Console.WriteLine($"{a.Owner}: {a.Balance}");Console.WriteLine($"{b.Owner}: {b.Balance}");Ravi: 0 Selva: 5000
Remember
A constructor has the class’s name, no return type, and runs on new.Writing any constructor removes the default parameterless one. Chain overloads with : this(...)to avoid duplicate setup code.Validate in the constructor so invalid objects can never exist.