What is a Constructor?
A constructor is a special method in a class or struct that gets called automatically when an instance of the object is created. It initializes the object and sets up its initial state.
Basic syntax:
public class Car { public string Model; // Constructor public Car() { Model = "Audi"; } }
Types of constructors available in C#.
Default Constructor
A default constructor is one that takes no parameters. If you don't define any constructor, C# provides a default constructor automatically.
Example:
public class Person { public string Name; // Default constructor public Person() { Name = "Test"; } }
Use Case:
Initialize default values when the object is instantiated.
Parameterized Constructor
A parameterized constructor allows you to _pass parameters _when creating an object. This helps initialize an object with custom values.
Example:
public class Person { public string Name; public int Age; // Parameterized constructor public Person(string name, int age) { Name = name; Age = age; } }
Use Case:
Provides flexibility to initialize objects with different values.
Copy Constructor
A copy constructor creates a new object by copying data from an existing object of the same class.
Example:
public class Product { public string Name; public double Price; // Copy constructor public Product(Product p) { this.Name = p.Name; this.Price = p.Price; } }
Use Case:
Useful in cloning objects.
Static Constructor
A static constructor is used to initialize static data members _of a class or to perform actions that only need to happen once.
Automatically _called once, before the first instance is created or any static members are accessed.
Example:
public class Logger { static Logger() { Console.WriteLine("Logger Initialized"); } }
Use Case:
Initialize static fields, set up logging, read configuration files, etc.
📌 Key Notes:
- No parameters
- No access modifiers
- Executes once before the first object or static member is accessed
Private Constructor
A private constructor restricts the instantiation of a class from outside. It is commonly used in singleton patterns or_ static classes_.
Example:
public class Configuration { private Configuration() { // Prevent external instantiation } }
Use Case:
Prevent object creation; enforce controlled access via static members.
Constructor Overloading
C# allows constructor overloading, which means a class can have multiple constructors with different parameter lists.
Example:
public class Rectangle { public int Width; public int Height; public Rectangle() { Width = 10; Height = 20; } public Rectangle(int width, int height) { Width = width; Height = height; } }
Use Case:
Provide flexibility in object creation.
Happy coding! 👨💻👩💻
Top comments (0)