C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Constructor

In this tutorial, we'll cover the basics of constructors in C#. A constructor is a special method in a class or struct that is called when an object is created. Constructors are used to initialize the object's fields and properties with default or provided values.

  • Set up the environment

Create a new C# Console Application project in Visual Studio.

  • Create a sample class

Create a sample class called Person with the following fields, properties, and methods:

public class Person
{
    // Fields
    public string Name;
    public int Age;

    // Methods
    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
    }
}
  • Add a constructor

A constructor has the same name as the class and does not have a return type. To add a constructor to the Person class, add the following method:

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

Now, when you create an instance of the Person class, you can pass the name and age as arguments, and the constructor will initialize the object's fields.

  • Instantiate the class and call the constructor

In the Main method, create an instance of the Person class and pass the arguments for the constructor:

static void Main(string[] args)
{
    // Instantiate the Person class using the constructor
    Person person = new Person("John Doe", 30);

    // Call the method
    person.Greet();

    Console.ReadLine();
}

When you run the Console Application, you should see the following output:

Hello, my name is John Doe and I am 30 years old.
  • Default constructor

If you don't define a constructor for a class, C# automatically provides a default constructor with no parameters, also known as the parameterless constructor. The default constructor initializes fields to their default values (0 for numeric types, null for reference types, and false for bool).

In the Person class example above, if you remove the custom constructor, C# will provide a default constructor, and you can create an instance of the Person class without passing any arguments:

Person person = new Person();

However, if you define a custom constructor with parameters, the default constructor is no longer provided automatically. If you still want to have a parameterless constructor, you need to define it explicitly:

public Person()
{
    Name = "Unknown";
    Age = 0;
}

In this tutorial, we've covered the basics of constructors in C#. Constructors are special methods that are called when an object is created, and they are used to initialize the object's fields and properties. By using constructors, you can ensure that your objects are initialized with appropriate values and make your code more robust and maintainable.

  1. C# constructor example:

    • Description: A constructor in C# is a special method that is called when an object of a class is created. It typically initializes the object's state.
    • Code:
      public class MyClass
      {
          // Constructor
          public MyClass()
          {
              Console.WriteLine("Constructor called!");
          }
      }
      
      // Usage
      MyClass myObject = new MyClass(); // Output: Constructor called!
      
  2. Parameterized constructors in C#:

    • Description: Introducing parameterized constructors that accept parameters during object creation.
    • Code:
      public class Person
      {
          public string Name;
      
          // Parameterized constructor
          public Person(string name)
          {
              Name = name;
          }
      }
      
      // Usage
      Person person = new Person("John");
      
  3. Constructor overloading in C#:

    • Description: Illustrating how to define multiple constructors with different parameter lists.
    • Code:
      public class Calculator
      {
          // Default constructor
          public Calculator()
          {
              // Initialization logic
          }
      
          // Parameterized constructor
          public Calculator(int initialValue)
          {
              // Initialization logic with parameter
          }
      }
      
      // Usage
      Calculator calc1 = new Calculator();
      Calculator calc2 = new Calculator(42);
      
  4. Private and public constructors in C#:

    • Description: Showing the use of access modifiers for constructors to control their visibility outside the class.
    • Code:
      public class Singleton
      {
          // Private constructor
          private Singleton()
          {
              // Initialization logic
          }
      
          // Public method to create or access the instance
          public static Singleton GetInstance()
          {
              return new Singleton();
          }
      }
      
  5. C# constructor chaining:

    • Description: Discussing constructor chaining, where one constructor calls another within the same class.
    • Code:
      public class MyClass
      {
          public MyClass() : this("Default")
          {
              // Additional initialization logic for the default constructor
          }
      
          // Parameterized constructor
          public MyClass(string value)
          {
              Console.WriteLine($"Constructor called with value: {value}");
          }
      }
      
      // Usage
      MyClass defaultObject = new MyClass(); // Output: Constructor called with value: Default
      
  6. Static constructors in C#:

    • Description: Introducing static constructors, which are used to initialize static members of a class.
    • Code:
      public class Logger
      {
          // Static constructor
          static Logger()
          {
              Console.WriteLine("Logger initialized.");
          }
      
          // Other members...
      }
      
      // No need to create an instance; static constructor is called automatically
      
  7. Using base class constructors in C#:

    • Description: Demonstrating how to use the base keyword to invoke the constructor of the base class in a derived class.
    • Code:
      public class Animal
      {
          public Animal(string name)
          {
              Console.WriteLine($"Animal named {name} created.");
          }
      }
      
      public class Dog : Animal
      {
          public Dog(string name) : base(name)
          {
              Console.WriteLine($"Dog named {name} created.");
          }
      }
      
      // Usage
      Dog myDog = new Dog("Buddy");