0
0
C Sharp (C#)programming~5 mins

Constructors and initialization in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Constructors help create objects with initial values. They set up things so your object is ready to use.

When you want to create a new object with specific starting values.
When you want to make sure an object always has certain data set.
When you want to run some setup code right when an object is made.
When you want to create multiple objects with different initial settings.
When you want to avoid forgetting to set important values after creating an object.
Syntax
C Sharp (C#)
class ClassName
{
    // Constructor
    public ClassName(parameters)
    {
        // Initialization code
    }
}

The constructor has the same name as the class.

It does not have a return type, not even void.

Examples
This constructor sets the Name when creating a Person.
C Sharp (C#)
class Person
{
    public string Name;

    public Person(string name)
    {
        Name = name;
    }
}
This constructor sets a default Year if no value is given.
C Sharp (C#)
class Car
{
    public int Year;

    public Car()
    {
        Year = 2024; // default year
    }
}
This constructor takes two values to set both Title and Author.
C Sharp (C#)
class Book
{
    public string Title;
    public string Author;

    public Book(string title, string author)
    {
        Title = title;
        Author = author;
    }
}
Sample Program

This program creates a Dog with a name and age using a constructor. Then it calls Bark to show the dog's info.

C Sharp (C#)
using System;

class Dog
{
    public string Name;
    public int Age;

    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void Bark()
    {
        Console.WriteLine($"{Name} says: Woof! I am {Age} years old.");
    }
}

class Program
{
    static void Main()
    {
        Dog myDog = new Dog("Buddy", 3);
        myDog.Bark();
    }
}
OutputSuccess
Important Notes

If you don't write a constructor, C# gives a default one with no parameters.

You can have many constructors with different parameters (called overloading).

Use constructors to avoid forgetting to set important data after creating objects.

Summary

Constructors set up new objects with starting values.

They have the same name as the class and no return type.

You can have multiple constructors with different inputs.