C#
Beginner
1 min read
Classes, Properties, and Constructors
Example
// Classes, auto-properties, init-only, and primary constructors
// Traditional class with auto-implemented properties
public class Product
{
public int Id { get; private set; }
public string Name { get; set; }
public decimal Price { get; set; }
// Primary fields computed from constructor args
public string Category { get; init; }
public Product(int id, string name, decimal price, string category)
{
Id = id;
Name = name;
Price = price;
Category = category;
}
public override string ToString() =>
$"[{Id}] {Name} ({Category}) — ${Price:F2}";
}
var p = new Product(1, "Laptop", 999.99m, "Electronics");
Console.WriteLine(p);
// Object initialiser — sets public settable properties
var p2 = new Product(2, "Phone", 699.99m, "Electronics")
{
Name = "Smartphone" // can override in initialiser
};
Console.WriteLine(p2);
// C# 12 primary constructor (great for simple types)
public class Point(double x, double y)
{
public double X { get; } = x;
public double Y { get; } = y;
public double DistanceTo(Point other) =>
Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
public override string ToString() => $"({X}, {Y})";
}
var a = new Point(0, 0);
var b = new Point(3, 4);
Console.WriteLine($"Distance: {a.DistanceTo(b)}"); // 5