Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Static Class
2.1.
Example Code in C#: 
3.
Static Variable
3.1.
Example Code in C#: 
4.
Static Method
4.1.
Example Code in C#: 
5.
Static Constructor
5.1.
Example Code in C#: 
6.
Frequently Asked Questions
6.1.
What are constructors in C#?
6.2.
What are the main properties of a static constructor?
6.3.
What are the limitations of the static keyword?
6.4.
What is the difference between static constructors and non-static constructors?
6.5.
Can you overload a static constructor?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Static Keyword in C#

Author Lucifer go
2 upvotes
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Static is a modifier in C# that can be implemented using the keyword static before any C# member. These members include classes, variables, constructors, functions, operators, properties, and events. A static member can be accessed with the name of its class directly.

Static Class

A static class, like all the other members, is declared with the help of a static keyword. A static class can contain only static data members, static methods, and a static constructor. One cannot create objects of the static class. Static classes are sealed, which means one cannot inherit a static class from another class, and thus inheritance is not allowed.

Example Code in C#: 

using System;

// A static class is created using a static keyword
static class Fruit {

   // Static data members of Fruit
   public static string Fruit_Name = "Apple";
}
// Driver Code
public class GFG {
   static public void Main()
   {
     // Accessing the static data members of Fruit
       Console.WriteLine("Fruit name is : {0} ", Fruit.Fruit_Name);
   }
}


Output: 

Fruit name is: Apple 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Static Variable

The static keyword is used to declare a static variable. When a variable is marked as static, a single copy of the variable is made at the class level and shared across all objects. Static variables are accessible by using the class name; they do not need the use of an object.

Example Code in C#: 

using System;

class Fruit {

   // Creating static variable
   public static string Fruit_Name = "Orange";
}

// Driver Class
public class GFG {
   static public void Main()
   {
       // Accessing the static variable
       Console.WriteLine("Fruit name is  : {0} ", Fruit.Fruit_Name);
   }
}


Output: 

Fruit name is: Orange 

Static Method

The static keyword can also be used to declare a static method. The name of the class is used to access static methods. A static method can access static and non-static fields; static fields can be accessed directly without using a class name, but non-static fields require the use of objects.

Example Code in C#: 


using System;
class Nparks {
 
    static public int t = 100;
 
    // Creating static method
    // Using static keyword
    public static void total()
    {
        Console.WriteLine("Total number of tigers present in India is :{0}", t);
    }
}
 
// Driver Class
public class GFG {

    static public void Main()
    {
      // Class name is used to access the static method
        Nparks.total();
    }
}


Output: 

Total number of tigers present in India is :100

Static Constructor

A static constructor is declared with the help of a static keyword. Static Constructor has to be invoked only once in the class and invokes automatically during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and executed only once.

Example Code in C#: 

using System;
 
class C1 {
 
    // invoked before the first instance is run.
    static C1()
    {
        // This line occurs only once.
        Console.WriteLine("Example of Static Constructor");
    }
 
    // Instance constructor.
    public C1(int j)
    {
        Console.WriteLine("This is the Instance Constructor " + j);
    }
 
    // Instance method.
    public string c1_detail(string name, string sport)
    {
        return "Name: " + name + " Sport: " + sport;
    }
 
    // Main Method
    public static void Main()
    {
 
        // Both Static and instance constructors are invoked
        C1 obj = new C1(1);
        Console.WriteLine(obj.c1_detail("Sunil", "Football"));
        // only instance constructor will be invoked
        C1 ob = new C1(2);
        Console.WriteLine(ob.c1_detail("Sweta", "Tennis"));
    }
}


Output: 

Example of Static Constructor

This is the Instance Constructor 1

Name: Sunil Sport: Football

This is the Instance Constructor 2

Name: Sweta Sport: Tennis

Frequently Asked Questions

What are constructors in C#?

A constructor is a class's custom method that is automatically called whenever a new class instance is created. A function constructor, like methods, includes a collection of instructions performed when an object is created. It provides data for members of the same class initial values.

What are the main properties of a static constructor?

  • It can’t be called directly and when it is executing, then the user has no control.
  • It does not take access modifiers or any parameters.
  • It is called automatically to initialize the class before the first instance is non-static execute created.

What are the limitations of the static keyword?

  • The static keyword cannot be used by indexers, finalizers, or types other than classes.
  • An instance cannot reference a static member.
  • In C#, it is not allowed to use this to reference static methods or property accessors.
  • In C#, if a static keyword is used with the class, then the class will always contain static members.

What is the difference between static constructors and non-static constructors?

Can you overload a static constructor?

Overloading is possible for non-static constructors but not for static constructors. Based on the parameter criteria, overloading is done. We can't overload it if the arguments can't be sent to the static constructors.

Also Read About - singleton design pattern in c# 

Conclusion

In this article, we have extensively discussed Static Keywords in C# and their implementation with classes, variables, methods, and constructors.

After reading about the Static Keywords in C#, are you not feeling excited to read/explore some articles on the other topic i.e. Programming in IoT and learning Ruby? Don't worry; Coding Ninjas has you covered. To learn, see more blogs on RubyRuby Documentation, and Programming Language for IoT.
Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass