Static Keyword in C# Tutorial | Learn with Examples

Static Keyword in C# Tutorial | Learn with Examples

static keyword in c ACTE

About author

Manish Kiran (C# Developer )

Manish Kiran is a C# developer expert and subject specialist who has experience with Git, WPF, WinForms, C#,.Net, SQL, .NET Development, VB, .NET Framework,.NET Core, SVN, and Mercurial. His articles help the learners get insights into the domain.

Last updated on 02nd Feb 2022| 1905

(5.0) | 18509 Ratings
    • Introduction
    • Static variable in C#
    • Static Methods in C#
    • Static Class in C#
    • What is the Static Keyword?
    • What is the static Keyword in C#?
    • Static catchphrase can be utilized in 3 situations
    • Model – static field and technique
    • Features of a static variable and static strategy
    • Focuses To Remember
    • Why C# primary technique is static?
    • Rules for static Constructor
    • Scopes of Static Keywords in C#
    • Advantages
    • Disadvantages
    • The constraint of utilizing static keywords in C#
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction :-

      The static Keyword in C# language is utilized to pronounce static classes and static class individuals. The static classes and static class individuals like constructors, fields, properties, techniques, and occasions are valuable when just one duplicate of the article (class or class individuals) are required and divided between all cases (objects) of a kind (and individuals).

      We should improve on it. Suppose, you have a class “CSharpCorner” that addresses the C# Corner site, its properties, and its capacities. The CSharpCorner class has four properties, Founder, YearFounded, Location, and Description. We realize that this multitude of properties are fixed and they won’t change paying little heed to the number of examples of CSharpCorner type are made by different projects or classes. This is an ideal illustration of a static class and static properties.


      Static variable in C# :-

      A variable can be proclaimed as static.

      Contextual analysis, At the point when we would rather not make numerous occurrences of a variable, i.e., we need to get to similar worth across different cases of class, then, at that point, we can choose a static variable. To get to a static variable we don’t have to make an object of the class. It tends to be open by the class name.


      Static Methods in C# :-

      Contextual analysis, Whenever we have a situation that concentrates more on the result just with next to no prerequisite to store or recover information that is remarkable to a particular occasion of a class, then, at that point, we can choose Static Methods. To get to the static strategies likewise we want to utilize the class name. No occasion is required.


       Static Keyword in C#
      Static Keyword in C#

      Static Class in C# :-

      Contextual investigation, At the point when we have all part capacities and information part in a class announced as static, we ought to pronounce the class as Static. Along these lines, all in all, we can say a static class ought not to contain any non-static fields/strategies.


      What is the Static Keyword?

    • The Static catchphrase is utilized to demonstrate that a part factor has a place with the actual class. When applied to a technique, then, at that point, the strategy has a place with the class and not to occurrences of the class. Similar applies to properties of a class. Factors or techniques proclaimed as static are alluded to as class variables.
    • Expecting a class is made with static strategies, then, at that point, we don’t need to make an occasion of the class to utilize the static strategy.

    • Course Curriculum

      Learn Advanced C Programming Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      When is it Necessary to utilize Static Keyword?

      A static catchphrase is utilized when it isn’t important to make different occurrences of the variable. This implies that a solitary variable exists and can be gotten to across different occurrences of the class.


      The static catchphrase in C# with Example:

    • We can characterize class individuals as static utilizing the static catchphrase. At the point when we pronounce an individual from a class as static, it implies regardless of the number of objects of the class are made, there is just one duplicate of the static part.
    • The catchphrase static suggests that just one example of the part exists for a class. Static factors are utilized for characterizing constants because their qualities can be recovered by conjuring the class without making an occurrence of it.

    • Coming up next is a model appearance the use of static factors −

      Model,

      • utilizing System
      • namespace StaticVarApplication
      • class StaticVar
      • public static int num
      • public void count()
      • num++
      • public int getNum()
      • return num
      • class StaticTester
      • static void Main(string[] args)
      • StaticVar s1 = new StaticVar()
      • StaticVar s2 = new StaticVar()
      • s1.count()
      • s1.count()
      • s1.count()
      • s2.count()
      • s2.count()
      • s2.count()
      • Console.WriteLine(“Variable num for s1: {0}”, s1.getNum())
      • Console.WriteLine(“Variable num for s2: {0}”, s2.getNum())
      • Console.ReadKey()
      • Output
      • “Variable num for s1:
      • Variable num for s2: 6

      What is the static Keyword in C#?

      The static catchphrase in C# language is utilized to proclaim static classes and static class individuals. … This is an ideal illustration of a static class and static properties. Note. You can change static part esteems however the last refreshed worth will be accessible to all projects or guests that call a static part.


      Static is a modifier in C# which is appropriate for the accompanying:

    • Classes
    • Factors
    • Techniques
    • Constructor

    • It is likewise pertinent to properties, occasion, and administrators. To make a static member (class, variable, techniques, constructor), go before its assertion with the Keyword static. Whenever a part is pronounced static, it very well may be gotten to with the name of its group straightforwardly.


      Static Class:

      A static class is proclaimed with the assistance of static Keyword. A static class can contain static information individuals, static techniques, and a static constructor. It isn’t permitted to make objects of the static class. Static classes are fixed, which implies one can’t acquire a static class from another class.


      Model:

      • C#
      • // C# program to represent the
      • // idea of a static class
      • utilizing System;
      • // Making static class
      • // Utilizing static catchphrase
      • static class Tutorial {
      • // Static information individuals from Tutorial
      • public static string Topic = “Static class”;
      • }
      • // Driver Class
      • public class GFG {
      • // Primary Method
      • static public void Main()
      • {
      • // Getting to the static information individuals from Tutorial
      • Console.WriteLine(“Topic name is : {0} “, Tutorial.Topic);
      • }
      • }
      • Output:
      • “The point name is Static class
      • we will talk about on Static keyword in C#.”

      Static catchphrase can be utilized in 3 situations :-

    • For Data individuals
    • For Methods
    • For Constructors

    • Static Data Member:

      If you pronounce any factor as static, it is a known static variable.

    • The static variable can be utilized to allude to the normal property of all protests (that isn’t one of a kind for each article) for example organization name of employees, college name of understudies, and so on
    • The static variable gets memory just a single time in the class region at the hour of class stacking.

    • Model:

      • C#
      • // C# program to show the
      • // idea of static variable
      • utilizing System;
      • class Vehicle {
      • // Making static variable
      • // Utilizing static catchphrase
      • public static string Model_color = “Dark”;
      • }
      • // Driver Class
      • public class GFG {
      • // Principle Method
      • static public void Main()
      • {
      • // Getting to the static variable
      • // utilizing its class name
      • Console.WriteLine(“Color of XY model is : {0} “,
      • Vehicle.Model_color);
      • }
      • }
      • Output:
      • The shade of XY model is: Black

      Static Data Method:

      On the off chance that you apply static catchphrase with any strategy, it is known as static technique.

    • A static strategy has a place with the class as opposed to the protesting of a class.
    • A static strategy can be summoned without the requirement for making an occurrence of a class.
    • static technique can get to static information part and can change its worth.
    • Static strategy is gotten to utilizing class name.method name

    • Model:

      • C#
      • // C# program to show the
      • // idea of static technique
      • utilizing System;
      • class Nparks {
      • static public int t = 104;
      • // Making static strategy
      • // Utilizing static catchphrase
      • public static void aggregate()
      • {
      • Console.WriteLine(“Total number of public parks”+
      • ” present in India is :{0}”, t);
      • }
      • }
      • // Driver Class
      • public class GFG {
      • // Principle Method
      • static public void Main()
      • {
      • // Getting to the static strategy
      • // utilizing its class name
      • Nparks.total();
      • }
      • }
      • Output:
      • “The absolute number of public parks present in India is:104.”

      Course Curriculum

      Get JOB Oriented C Programming Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      Model – static field and technique :-

      This model peruses the name and ID of another representative, augments the worker counter by one, and presents the data for the new worker and the new number of representatives. This program peruses the current number of representatives from the console. C#Copy


      Model – Static Instatement:

      This model shows that you can instate a static field by utilizing another static field that isn’t yet proclaimed. The outcomes will be indistinct until you unequivocally allot a worth to the static field.


      • C#Copy
      • class Test
      • {
      • static int x = y;
      • static int y = 5;
      • static void Main()
      • {
      • Console.WriteLine(Test.x);
      • Console.WriteLine(Test.y);
      • Test.x = 99;
      • Console.WriteLine(Test.x);
      • }
      • }
      • /*
      • Yield:
      • 0
      • 5
      • 99
      • */

      Features of a static variable and static strategy :-

    • A static variable and a static strategy have a place with the class where they are made, accordingly, a static variable is known as a class variable and a static technique is known as a class strategy.
    • A static variable and a static technique can be gotten to by their group name with a sports administrator.
    • Static Variable
      Static Variable
    • Whenever a static variable is instated with a worth, its worth continues as before an incentive for every one of the objects of a class.
    • A solitary duplicate of both, a static variable and a static technique is shared by every one of the objects of a class.

    • Focuses To Remember :-

    • It can’t be called straightforwardly.
    • Whenever it is executing, then, at that point, the client has no control.
    • It doesn’t take access modifiers or any boundaries.
    • It is called consequently to introduce the class before the principal example is made.

    • Why C# primary technique is static?

      The C# primary technique is static since the object isn’t expected to call static strategy on the off chance that it was non-static technique, the compiler makes object first call principle () strategy that will lead the issue of additional memory allotment.


      Static Constructor:

    • A static constructor is an exceptional constructor that gets called before the principal object of the class is made. It is utilized to introduce any static information or to play out a specific activity that requires performed once as it were.
    • The hour of execution of static constructor isn’t known yet it is certainly before the main item creation – might be at the hour of stacking get together.

    • Example1 :

      • utilizing System;
      • public class Student
      • {
      • static Student ()
      • {
      • // instate static individuals as it were.
      • }
      • // different strategies here.
      • }

      Example2 :

      • utilizing System;
      • public class MyStaticClass
      • {
      • static int count;
      • static MyStaticClass()
      • {
      • count = 0;
      • Console.WriteLine(“Static class is introduced”);
      • }
      • public static void MyMethod(string name)
      • {
      • Console.WriteLine(“Static class is introduced ” + name);
      • }
      • }
      • MyStaticClass.MyMethod(“Steve”) ;//strategy call
      • //constructor will be called naturally
      • Output:
      • “The static class is introduced, Steve.”

      Rules for static Constructor :-

    • A class can have just a single static constructor
    • Static constructor cannot have any boundary
    • Static constructor cannot have any entrance specifier
    • It is utilized to instate the static information individuals from the class
    • for quite a few article creations, the static constructor gets executed just a single time
    • The static constructor gets executed when the class is utilized
    • Static constructor cannot be conjured by the developer expressly

    • Scopes of Static Keywords in C# :-

      Access of a static variable/static strategy inside the scope of its group: Inside the scope of its group, a static variable or a static strategy can be gotten to straightforwardly or by utilizing its class name and a speck administrator.


      Inaccurate access of a static variable/static technique outside the scope of its group gives a mistake: Outside the scope of its group, a static variable or a static strategy can’t be gotten to directly (without utilizing its class name with a dab administrator).


      A static variable and a static strategy have a place with the class wherein they are proclaimed, and they have no personality of their own external the scope of their group, consequently, attempting to straightforwardly get to a static variable or a static technique outside the scope of their group, gives an incorporate blunder.


      Right access of a static variable/static technique outside the scope of its group. Outside the scope of its group, a static variable or a static technique must be gotten to by utilizing its class name and a dab administrator.


      Can’t straightforwardly get to example factors/strategies from inside a static strategy. You can get to static factors or call static techniques from a static strategy, and we can’t get to an occasion variable or occurrence strategies from inside a static technique. Allow us to see a model.


      Default worth of a static variable : A static variable and a static strategy for a class are accessible and open even before making any objects of this class. Henceforth, on the off chance that a static variable isn’t instated to worth, it is given default esteem when its class is stacked interestingly by the Common Language Runtime (CLR) arrangement of C#.A solitary duplicate of static variable is shared by every one of the objects of the class.


      Advantages :-

      Static individuals/strategies are utilized as in aide classes say like Math or in constants classes. which assists different articles with using Strings or helpful capacities for which you don’t have to make objects yet conjured utilizing Class name.


      Model – singleton objects are conjured utilizing a static capacity.


      Disadvantages :-

      Static individuals are essential for class and in this way stay in memory till application ends and can’t be ever trash gathered. Utilizing overabundance of static individuals at some point predicts that you neglect to plan your item and attempt to cop with static/procedural programming. It indicates that the item arranged plan is compromised. This can bring about memory over a stream.


      Additionally, sure detriments are assuming you make any technique static in Java for instance you cannot supersede any static strategy in Java so it creates testing more earnestly you cannot supplant that strategy with mock. Since static technique keeps up with worldwide state, they can establish inconspicuous bug in simultaneous climate which is difficult to recognize and fix.


      The constraint of utilizing static keywords in C# :-

    • Static catchphrase can’t be utilized by indexers, finalizers, or types other than classes.
    • A static part isn’t referred to through an occurrence.
    • In C#, it isn’t permitted to utilize this to reference static strategies or property accessors.
    • In C#, if static Keyword is utilized with the class, the static class generally contains static individuals.

    • C and C Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion :-

      The catchphrase static is admission to unadulterated OOP. Anyway, a twofold-edged catchphrase doesn’t blend well in with the variable state. Not utilizing it shrewdly essentially prompts huge difficulties. In any case, it tends to be a decent companion whenever utilized carefully.


    Name Date Details

    14-Oct-2024

    (Mon-Fri) Weekdays Regular

    16-Oct-2024

    (Mon-Fri) Weekdays Regular

    19-Oct-2024

    (Sat,Sun) Weekend Regular

    19-Oct-2024

    (Sat,Sun) Weekend Fasttrack