What are Static & Non-Satic Class Members in C#?
All fields, methods, constructors, properties, events, and indexers are known as Class members. There are 2 type of members, Static and Non-Static. Static member contains Static keyword in front of them. We can have static fields, static methods, static constructors etc. If value of a member is not changing on creation of every new object, you can make that member Static. Otherwise, you will end up creating multiple copies of the same member in the memory and it will consume more memory depends upon the type of the member.
If you make the member Static, it will be shared by all the objects which you will create. There will always be only 1 copy of the Static member in the memory, no matter how many objects you will create. You cannot use this keyword in front of Static members because this keyword can only be used in front of Non-Static members. Instead of using this keyword, you can use Class name in front of it to access (ClassName.StaticMember). You have to follow the same case, if the Static member is public and you want to access it from another Class because accessing it at object level is not allowed. All Non-Static members can only be accessed at object level. The below given diagram demonstrates that in case of Non-Static, 2 objects points to 2 copies of same member which they want to access, but when we mark that member, Static those 2 objects points to only 1 copy of that member.
Like all other Class members, a Constructor can also be Static. Static Constructor is basically used to initialize Static members. You are not allowed to use any access modifier in front of it because it is private by default and also it does not take any parameter. Static Constructor is called automatically even before the object or instance level Constructors and it is called only once, no matter how many objects you create of that Class. A very good example is given below, where we are creating an object of the Student class and a Static constructor is automatically called and initializing the Static field.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Hello { class Student { static string _studentname; static string _teachername; static Student() { _studentname = "Albert Pinto"; } public Student(string name) { _teachername = name; } public void PrintName() { Console.WriteLine(_studentname); Console.WriteLine(_teachername); } } class Program { static void Main(string[] args) { Student S = new Student("Mark Johnson"); S.PrintName(); } } }