What is Static Class in C# and when to use with real example
In C#, a static class is a class that cannot be instantiated and can only contain static members, such as static methods, static properties, and static fields. It is primarily used as a container for utility functions or extension methods that can be accessed without creating an instance of the class.
The main features of static classes are as follows:
- They can only contain static members.
- They can't be instantiated or inherited because static classes are sealed and can't contain instance constructors. However, the developer can create static constructors to initialize the static members.
The following code is an example of a static class. We have already learned that all members of the class are static.
public static class Product
// Static fields because Product is a static class
public static string Name = "Laptop";
return 10;
}
Let's see the example of static classes with their characteristics
We can create an instance of static class if you create instance of class you will get compile time error like Cannot create an instance of the static class 'Product' let's see example in below picture.
Static class cannot be inherited means you can child class from static class if you try to inherit static class then you will get compile time error 'MyItems' cannot drive from static class 'Product' let's see an example and try it yourself for best practice.
We cannot create instance members in the static class otherwise you will get this error 'GetDeliveryCharge' can't declare instance members in a static class
namespace SoftwareEngineerDotNet
public static class Product
{
public static string Location = "Delhi";
return 10;
}
class Program
{
static void Main(string[] args)
// Calling the static method
int result = Product.GetDeliveryCharge();
Console.ReadLine();
}
}
}
Note that static classes cannot be inherited, and they cannot have instance constructors. They are sealed by default, which means you cannot derive a class from a static class.
0 comments:
Post a Comment
Do not enter spam link