What is a Constructor?
A constructor is a special method in C# used to initialize objects of a class. It is automatically called when an object is created. Constructors typically set initial values for the object's fields or perform setup tasks.
Key Points About Constructors
- Constructor has the same name as the class.
- It does not have a return type, not even void.
- Automatically called when an object is created.
- A class can have multiple constructors with different parameters (constructor overloading).
- Ensures that the object starts in a valid state.
Types of Constructors in C#
- Default Constructor: No parameters. Sets default values.
- Parameterized Constructor: Takes arguments to initialize the object.
- Static Constructor: Initializes static members. Called once before the first object.
Example: Parameterized Constructor
using System;
class Car
{
public string Model;
public string Color;
// Constructor
public Car(string model, string color)
{
Model = model;
Color = color;
Console.WriteLine("Car object created!");
}
public void DisplayInfo()
{
Console.WriteLine($"Model: {Model}, Color: {Color}");
}
}
class Program
{
static void Main()
{
// Creating an object calls the constructor
Car myCar = new Car("BMW", "Red");
myCar.DisplayInfo();
}
}
Output
Car object created!
Model: BMW, Color: Red
No comments:
Post a Comment