Introduction: C# static constructor

In this post, we will learn about C# static constructor with an example.

Description:

In my previous posts I have explained various topics like Comments in C#, Disable right click on web page and images, Nullables in C# Collections in C#SortedSet in C#.Net,Stack in C#,Queue in C#.Net,LinkedList in C#.Net. Now in this post, I will explain about C# static constructor with appropriate example.
C# static constructor is helpful to initialize static fields.It can also be used to perform any action that is to be performed only once within program. It gets invoked automatically before even first instance is created or any static member is referenced.

  • C# static constructor cannot have any modifier or parameter with it.
  • C# static constructor is invoked implicitly. It can not be called explicitly.

Now,create  Console Application in Visual Studioin  and write below lines of code in it.

 

using System;
using System.Collections;

namespace ConsoleDemo
{
    public class Person
    {
        public int id;
        public String name;
        public static float height;
        public Person(int id, String name)
        {
            this.id = id;
            this.name = name;
        }
        static Person()
        {
            height = 5.3f;
        }
        public void display()
        {
            Console.WriteLine(id + " " + name + " " + height);
        }
    } 
    class Program
    {
        static void Main(string[] args)
        {
            Person a1 = new Person(11, "Raj");
            Person a2 = new Person(12, "Akshay");
            a1.display();
            a2.display();
            Console.Read();
        }
    }   
}
C# static constructor

C# static constructor

Summary

I hope you got an idea about C#.Net static constructor.
I would like to have feedback from my blog readers.
I hope after reading this article you will be able to do this.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website