This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Constructor Introduction


In this article we are going to discuss about constructor with examples in C#.

Constructor Introduction

A constructor is a special method in a class that is automatically called when an object of that class is created. It is used to initialize the object. Constructor name will same as of Class name.

using System;

namespace Constructorproject
{
    public class Person
    {
        public string FirstName;
        public string LastName;

        // Constructor
        public Person(string firstName, string lastName)
        {
            Console.WriteLine(firstName + " " + lastName);
        }
    }
    class Program
    {
        static void Main()
        {
            // Usage
            Person person = new Person("Rohatash", "Kumar");

            Console.ReadLine();
        }
    }
}

When to use constructors in real applications?

  1. Initialization - To set initial values for object attributes.
  2. Resource Allocation - To allocate resources like memory or file handles.
  3. Dependency Injection - To inject dependencies required by the object.

1. Initialization

To set initial values for object attributes.

using System;

namespace delegateproject
{
    public class Person
    {
        public string FirstName;
        public string LastName;

        // Initialization (Parameterized) Constructor
        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
            //Console.WriteLine(firstName + " " + lastName);
        }
    }
    class Program
    {
        static void Main()
        {
            // Usage
            Person person = new Person("Rohatash", "Kumar");

            Console.ReadLine();
        }
    }
}

2. Resource Allocation

To allocate resources like memory or file handles. This example demonstrates how a constructor can be used to allocate resources (opening a file) and how the destructor can be used to clean up those resources (closing the file)

using System;
using System.IO;

public class FileReader
{
    private StreamReader _reader;
    public string FilePath { get; }

    // Constructor
    public FileReader(string filePath)
    {
        FilePath = filePath;

        try
        {
            // Allocate the resource (open the file)
            _reader = new StreamReader(FilePath);
            Console.WriteLine("File opened successfully.");
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"File not found: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }

    // Method to read file content
    public string ReadFile()
    {
        if (_reader == null)
        {
            return "Reader is not initialized.";
        }

        try
        {
            return _reader.ReadToEnd();
        }
        catch (Exception ex)
        {
            return $"An error occurred while reading the file: {ex.Message}";
        }
    }

    // Destructor to clean up resources
    ~FileReader()
    {
        if (_reader != null)
        {
            _reader.Close();
            Console.WriteLine("File reader closed.");
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // Provide a valid file path
        string filePath = "example.txt";

        // Create an instance of FileReader
        FileReader fileReader = new FileReader(filePath);

        // Read the file content
        string content = fileReader.ReadFile();
        Console.WriteLine(content);
    }
}

3. Dependency Injection

To inject dependencies required by the object. This example illustrates how dependency injection allows you to decouple the Service class from the specific implementation of the ILogger interface, promoting flexibility and testability.

using System;

public interface ILogger
{
    void Log(string message);
}

public class ConsoleLogger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine($"Log: {message}");
    }
}

public class Service
{
    private readonly ILogger _logger;

    // Constructor Injection
    public Service(ILogger logger)
    {
        _logger = logger;
    }

    public void DoWork()
    {
        _logger.Log("Work is being done.");
        // Perform work
        Console.WriteLine("Service is doing work.");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // Manually create the dependency
        ILogger logger = new ConsoleLogger();

        // Inject the dependency into the service
        Service service = new Service(logger);

        // Use the service
        service.DoWork();
    }
}

Types of Constructors

There are several types of constructors, each serving a different purpose. Here are the main types of constructors.

Constructor in C#
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor

Prev Next