| by Arround The Web | No comments

How to Implement Static Methods and Constructors in C#

It goes without saying that OOP is extensive. It does come with its challenges and sometimes very annoying hoops to jump through but it is a powerful programming paradigm nonetheless.

Personal feelings about OOP aside, the major components of OOP are methods and constructors. Specifically, static methods and constructors.

In this tutorial, we will cover the fundamentals of building and working with static methods and constructors in C#.

Methods

Let us start with methods. A method is basically a function that is defined within a given class. A method carries out an operation and returns a value or void and supports the use of parameters.

Take the following example:

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}
class Program
{
    static void Main()
    {
        Calculator calculator = new Calculator();
        int result = calculator.Add(5, 7);
        Console.WriteLine(result);
    }
}

In the given example, the “Calculator” class has a method called “Add”. The method accepts two integer values, adds them, and returns an integer value.

This is a good example of a method. It contains an operation, parameters, and a return value.

What Is a Static Method?

Now, when we are talking about static methods, we are referring to methods that belong to the class rather than an instance of the object.

We mainly declare a static method using the static keyword. Once we declare it, we can invoke it without even creating an object from the class.

Unlike the instance methods (non-static), static methods perform operations without the need to access the object data.

public class Math
{
    public static int Square(int number)
    {
        return number * number;
    }
}

In this example, we define a class called “Math” that contains one static method called “Square”. The method accepts an integer parameter, performs the operation, and returns a value.

However, unlike a non-static method, we do not need to create an object from the class. We can simply access the method and perform our task as follows:

int sqr = Math.Square(199);
Console.WriteLine(sqr);

Notice the difference? That is how we can use the static methods.

Constructors

Let us move on to constructors.

A constructor is a special method that is automatically invoked whenever an instance of the class is created. The main role of constructors is to initialize the objects and mostly contains a similar name as the class into which it belongs.

NOTE: A constructor does not have a return type.

As you can guess, there are two main types of constructors:

  1. Instance constructors
  2. Static constructors

Instance Constructors

The use of an instance constructor is creating and initializing an instance of a class. An instance constructor however supports the parameters which allows it to set specific values for the object.

It can also be parameter-less.

The following shows the implementation of an instance constructor:

public class Car
{
    public string Model { get; set; }
    public int Mileage { get; set; }

    public Car(string model, int mileage)
    {
        Model = model;
        Mileage = mileage;
    }
}

class Program
{
    static void Main()
    {
        Car car = new Car("Benz", 3000);
        Console.WriteLine($"Model: {car.Model}, Mileage: {car.Mileage}");
    }
}

In this example, the “Car” class has an instance constructor called “Car” (very common to have similar names).

The “Car” constructor accepts the model and mileage parameters which allow it to set the custom values for any new object that are created from the class.

You will notice from this snippet:

Car car = new Car("Benz", 3000);

Static Constructors

Lastly, we have static constructors. Unlike the instance constructors, static constructors are used to initialize the class itself rather than the objects from the class.

Static constructors are called once and are automatically called by the Common Language Runtime when the class is loaded. This happens before any of the objects from the class are created or any static members are accessed.

NOTE: Nope, static constructors DO NOT support the parameters or access modifiers.

This is an example of a static constructor:

public class InitDb
{
    public static string ConnectionString { get; private set; }

    static InitDb()
    {
        Console.WriteLine("Initialiaing the class.");
        ConnectionString = "Server=localhost;Database=public;User=root;Password=mysql;";
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(InitDb.ConnectionString);
    }
}

In the given example, we define a static constructor called “InitDb”. It still has similar name to the class but contains the “static” keyword.

Once the main method runs, the “InitDB” class is initialized which automatically triggers the static constructor. We can then access the members.

Conclusion

In this tutorial, we taught you the most essential and powerful functionalities of static methods and constructors in C#. Like any other tutorials, we could not discuss everything in one tutorial. Feel free to reference the documentation for more details.

Share Button

Source: linuxhint.com

Leave a Reply