Working With Static In C sharp

Article by Mr Sandeep Soni on ”
Description

Working With Static In C sharp: The static keyword can be applied on data members, constructors, classes, methods, properties, and events. The static modifier makes an item non-instantiable.

 

 

C# program using static class
C# program using static class

 

: https://www.c-sharpcorner.com/article/working-with-static-in-c-sharp/
Please feel free to like and post comments on the article. Also Like the profile of “Sandeep Soni” to get future updates.

You can search the profile –
1. Search
2. under “People” tab
3. Type First Name “Sandeep”, Last Name “Soni”
4. click on the profile – Hit Like.

Introduction

This article is all about static in C#. It explains about,
Static members
Static constructor
Static methods and properties
Static class
Example using all these.
Description

The static keyword can be applied to data members, constructors, classes, methods, properties, and events. The static modifier makes an item non-instantiable.

Static members in C#

When are they loaded and how is the memory allocation,
A class is loaded when either

The static members of the class are accessed for the first time, or
When the first instance of the class is created.
A class once loaded will remain in memory permanently and also are all static members of that class.

For every new instance of a class, all the instance members are allocated memory as one unit, but static field members of a class are allocated memory only once, irrespective of the number of objects created, and they are allocated memory when the class is loaded. These members are also called class members and are accessed outside the class using the class name.

A public static member of a class can be used as a Global member of the application because it can be assessed using a class name from any part of the application.

Static Constructor in C#

It is a constructor with the static keyword.
It is used to initialize static members dynamically and is executed when the class is loaded.
It is invoked by the CLR when the class is loaded by it and hence cannot be overloaded nor can be declared with any accesses specifier like public or private.
Series of events that occur when the first object is created,

The class is loaded.
Static members are loaded and allocated memory.
The static constructor is executed.
An object is created and Instance members are loaded and allocated memory.
Instance constructor is executed.
4 and 5 repeats for a subsequent object.

Please follow and like us:
0

Leave a Reply

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