What is the use of static class in c#.net with example

What is the use of static |static class in c#|static class with example

If the class has with static keyword it becomes a static class. Static class can have static functions static variables and static properties. We can't create an object of static class and also we can't have sub-classes of static class. (no inheritance)


A static class contains only static members and static functions if they are not static we will not able to call anything of a static class.





what is the use of static class in c#.net with example


Static classes with static data members are nothing more than global variables. All static classes are sealed (you cannot derive them from a static class).

So, the question comes to mind, if we can't create an object and can't inherit then what is the use of the static class. (See Below)



using System;

 public static class Employee   // Static class
{
    public static string name;
    public static int age;
    public static string work()
    {
        return "Programming";
    }
}
class MainClass
{
    static void Main(string[] args)
    {
        Employee.work();      //Able to call by the class name
        Employee.age = 21;
        Employee.name = "SOMEONE NAME";
    }
}


Why we use the static class:

When we have the requirement to achieve something like global in our application and we don't want to create an object of class again and again (because object creating is the consumption of memory) then we have to go for static class. Simply we write the class name and use the (.) operator, we can call the members and functions available in the static class.


Note: Static class is controlled by CLR  and CLR provides the memory to the static class which means that the user has no control over the static class.
Static class behaves like a service or helper class.



Post a Comment

Post a Comment (0)

Previous Post Next Post