A constructor is a special method called automatically when an object is created. C# supports multiple constructors through overloading.
public class Point
{
public double X { get; set; }
public double Y { get; set; }
// Default constructor — no parameters
public Point()
{
X = 0;
Y = 0;
}
}
var origin = new Point();
Console.WriteLine($"{origin.X}, {origin.Y}"); // 0, 0
public class Point
{
public double X { get; }
public double Y { get; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public double DistanceTo(Point other) =>
Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
}
var a = new Point(0, 0);
var b = new Point(3, 4);
Console.WriteLine(a.DistanceTo(b)); // 5
public class Rectangle
{
public double Width { get; }
public double Height { get; }
// Delegates to the two-parameter constructor
public Rectangle(double side) : this(side, side) { }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
}
public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
public string Greet() => $"Hi, I'm {name}!";
}
var p = new Person("Alice", 30);
Console.WriteLine(p.Greet()); // Hi, I'm Alice!