C# static constructor Tutorial with Examples

C# static constructor Tutorial with Examples

Today, We want to share with you C# static constructor Tutorial with Examples.
In this post we will show you C# static constructor, hear for C# Static Method, Class and Constructor we will give you demo and example for implement.In this post, we will learn about Static constructor in CSharp(C#.Net) with an example.

Introduction: C# static constructor

In this post, we will learn about C# static constructor with an 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();
        }
    }   
}

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about C# static constructor.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment