A class in C sharp declared with static keyword is a C# static class. The static class prevents the object creation and can be used directly without creating any instance of class. A class that is not a static class is used after creating its object with new keyword. But the class that is static is used directly without creating its object
What is the benefit of using static class in C#?
1. It makes program faster and simpler because there is no need to create object of static class.
2. Its function can be directly called followed by the class name so, you can use its function anywhere in your program easily.
3. Its variable can also be accessed directly.
Guideline to using static class C#
1. The static class can contain only static members.
2. The static class cannot be instantiated.
3. The static class is a sealed class so you cannot inherit and override its members.
4. Usually it doesn’t contain constructors however; it is possible to declare a static constructor within static class..
Static class
When a class has been defined as static, it is not creatable using the new keyword , and it can contain only static members or fields
The main feature of static class
One is no object of static class can be created
Static class must contain only static members
We do need to make any instance of this class, all members are accessible with its own name.
Static class can’t implement interface
Static class contains only static constructor.
Static class is implicitly sealed.
Static class cannot have instance constructor
Can have only one constructor without any parameter
Can have only one constructor without any parameter
This makes program fast and simpler because there is no need to create object of static class.
static class Perl
{
// Cannot declare instance members in a static class!
// int _test;
// This is ok.
public static bool _ok;
// Can only have static methods in static classes.
public static void Blend()
{
Console.WriteLine("Blended");
}
}
Output
Blended
public static class Rectangle
{
public static int CalculateArea(int width, int height)
{
return width * height;
}
}
Console.WriteLine("The area is: " + Rectangle.CalculateArea(5, 4));
No comments:
Post a Comment
Thank you for visiting my blog