In C# programming, a static is a keyword or modifier associated with the type rather than the instance. Nonetheless, accessing static members does not necessitate an instance. In C#, static can denote a field, method, constructor, class, property, operator, or event. This signifies that a static member is universally shared among all class objects, allowing access without the need to instantiate an object.
In C#, the static keyword serves as a modifier and can be utilized on the subsequent members:
The given CSS code snippet defines a placeholder diagram with a background gradient, border radius, padding, margin, and alignment properties. Within the diagram, there is an icon with specific styling for font size and margin, as well as text with a specified color and font size.
Here, we will explore each of these static keywords individually.
1) Static Classes
In C#, a static class is a type of class that is not designed for instantiation and comprises solely static members. To define a static class, the keyword "static" is utilized. These classes are commonly employed to structure utility functions or helper methods. They are sealed, indicating that inheritance from another class is not possible.
Rules of Static Class
There are several rules of a static class in C#. Some of them are as follows:
- It cannot be instantiated or inherited (it is inherently sealed).
- It can only have static members (fields, methods, properties, and many others).
- There are no instance members or constructors allowed.
- Indexers and destructors cannot be static or included.
- The var keyword is not permitted for static members; explicit type is required.
- Members are accessed using their ClassName.MemberName.
- It remains in memory throughout the application domain's lifespan.
Key features of Static Class
There are several key features of a static class in C#. Some of them are as follows:
- The static keyword is used to declare a static class.
- All of the members must be static.
- This property cannot be inherited or instantiated.
C# Static Class Example
Let's consider an example to demonstrate the concept of a static class in C#.
Example
using System;
// Static class
static class C# Tutorial
{
public static string App_Name = "Instagram";
public static string Version = "8.0.0";
public static void Display()
{
Console.WriteLine("The App name is: " + App_Name + " | The app Version is: " + Version);
}
}
// Separate Test class with Main method
class Test
{
static void Main()
{
C# Tutorial.Display();
}
}
Output:
The App name is: Instagram | The app Version is: 8.0.0
Explanation:
In this instance, we are examining a C# Tutorial showcasing a class with solely static elements (App_Name, Version, and Display), preventing instantiation. Subsequently, the Test class invokes the static function directly by referencing the class name, illustrating the practicality of static classes in consolidating utility or auxiliary functions.
2) Static Fields
In C# programming, static fields can be defined in a non-static class using the static keyword. These fields are accessible to all instances of the class, indicating they are associated with the class itself rather than any specific object.
Key features of Static Field
There are several features of a static field in C#. Some of them are as follows:
- A static field is only initialized once and has a single memory address.
- Any changes made to the static field by one object will be visible to all other instances of the same class.
- Static fields are useful for storing data or configurations that are the same across all instances.
C# Static Field example
Let's consider an instance to demonstrate a static field in C#.
Example
using System;
public class Account
{
public int accno;
public String name;
public static float rateOfInterest=8.8f;
public Account(int accno, String name)
{
this.accno = accno;
this.name = name;
}
public void display()
{
Console.WriteLine(accno + " " + name + " " + rateOfInterest);
}
}
class TestAccount
{
public static void Main(string[] args)
{
Account acc1 = new Account(101, "Jhonson");
Account acc2 = new Account(102, "Adam");
acc1.display();
acc2.display();
}
}
Output:
101 Jhonson 8.8
102 Adam 8.8
Explanation:
In this instance, we are examining an Account class featuring instance variables (accno, name) and a static variable (rateOfInterest) shared universally across all instances. Subsequently, we instantiate two account objects and showcase their particulars alongside the standardized interest rate.
C# Field Example to Change Static Field
If the value of a static field is modified, it will affect all instances of the class.
Example
using System;
public class Account
{
public int accno;
public String name;
public static float rateOfInterest=8.8f;
public Account(int accno, String name)
{
this.accno = accno;
this.name = name;
}
public void display()
{
Console.WriteLine(accno + " " + name + " " + rateOfInterest);
}
}
class TestAccount{
public static void Main(string[] args)
{
Account.rateOfInterest = 10.5f;//changing value
Account acc1 = new Account(101, "Jhonson");
Account acc2 = new Account(102, "Adam");
acc1.display();
acc2.display();
}
}
Output:
101 Jhonson 10.5
102 Adam 10.5
Explanation:
In this illustration, we are considering the class Account that contains a pair of instance variables (accno, name) and a single static variable (rateOfInterest) that is accessible by all instances. Within the Main function, the static variable is modified to 10.5f prior to the creation of two instances. Upon invoking the display function, both instances exhibit their unique account information alongside the identical adjusted interest rate.
3) Static Method
In C# programming, a static method is a method that can be invoked on the class directly without the need to instantiate a new object. This type of method has immediate access to static fields or other static methods within the class. The static keyword is utilized to define a static method.
Rules of Static Method
There are several rules for a static method in C#. Some of them are as follows:
- A static method is defined using the static keyword that was declared before the return type.
- It can be overloaded but cannot be overridden.
- Static members can only be accessed directly using a static method.
- Access to instance members is only possible when they are supplied as parameters.
Key Features of Static Method
There are several key features of a static method in C#. Some main features are as follows:
- Non-static members cannot be directly accessed.
- It was called with the class name.
- It is useful for functions or actions that are not dependent on object state.
C# Static Method Example
Consider an illustration to demonstrate the static method in C#.
Example
using System;
class C# Tutorial
{
public static int SquareNumber(int Num_ber)
{
return Num_ber * Num_ber;
}
}
class Test
{
static void Main()
{
Console.WriteLine("The Square of 10 is: " + C# Tutorial.SquareNumber(10));
}
}
Output:
The Square of 10 is: 100
Explanation:
In this instance, we are examining the SquareNumber function declared as static within the C# Tutorial class, enabling direct invocation by referencing the class name without requiring an instance. Subsequently, the main method invokes it to compute and exhibit the square of 10.
4) Static Constructor
In C# programming, the static constructor is frequently used to set up static members of a class. This constructor is automatically called once prior to accessing any static members or instantiating the class.
Rules for Static Constructor
There are several rules for a static constructor in C#. Some of them are as follows:
- It is declared using the static keyword. It doesn't take any parameters or access modifiers.
- Each class may only have one static constructor.
- The execution timing is unpredictable.
- It cannot be called directly.
- Once it is executing, the user has no control over C#.
- It is invoked automatically to initialize the class before the creation of the first instance.
C# Static Constructor Example
Let's consider an example to demonstrate the static constructor in C#.
Example
using System;
class C# Tutorial
{
public static string LogType;
static C# Tutorial()
{
LogType = "INFO";
Console.WriteLine("Static constructor is called.");
}
public static void Log(string message)
{
Console.WriteLine($"[{LogType}]: {message}");
}
}
class Program
{
static void Main()
{
C# Tutorial.Log("Application is started");
C# Tutorial.Log("Performing some of the tasks");
}
}
Output:
Static constructor is called.
[INFO]: Application is started
[INFO]: Performing some of the tasks
Explanation:
In this instance, we are examining a C# Tutorial where a static field LogType is initialized and automatically executed prior to the initial usage of the class. Subsequently, the log method utilizes this initialized value to display the log message on the console.
Limitations of Static Keyword
There are several limitations of a Static Keyword in C#. Some of them are as follows:
- The "this" keyword is incompatible with the static keyword.
- Static classes are unable to implement interfaces.
- Indexers, destructors, and events cannot be kept static.
- Static members cannot be accessed through an object reference.
Conclusion
In summary, the C# static keyword is primarily employed to declare members (such as variables, methods, constructors, or classes) that are associated with the class itself rather than individual objects. Static members are shared among all objects, so modifications made via one object are visible in all others. They are beneficial for shared data and utility functions. Nonetheless, they are unable to directly interact with non-static (instance) members as they are connected to the class.
C# Static FAQs
Yes, a non-static method in C# can access and interact with a static field.
Yes, a dynamic method is able to access static properties directly as static elements are inherent to the class.
Is it permissible to utilize this keyword within static methods in C#?
No, it pertains to a specific occurrence, and static methods are not linked to any particular instance.
In C#, a static constructor is executed only once per application domain.
Only one time for each type, and this should be done prior to accessing any static member or creating an instance.
4) Can static functions be overloaded in C#?
In C#, static methods have the ability to be overloaded in a similar manner to instance methods.
5) Is it possible for a static class to contain instance members in C#?
In C# programming, a static class is limited to containing static fields, methods, and constructors.