Monday, 6 January 2020

why and when Static Class in C# with examples

A static class is basically the same as a non-static class, but there in one difference, a static class cannot be instantiated, means we cannot use new keyword to create an object of the class. Even we cannot create any parameterized constructor because to pass the constructor value we need to create object, we will check all these points in more detail in this article.
When we can use static class?
We have a class Math in C#, let’s check it’s methods and operation. Say Math.Min, it takes two values of different data types and return minimum one, similarly Max, Round, Floor, Ceiling. If you notice all these methods take some values and operate only those provided values. So a static class should be container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields.
What is a static class?
A static class is similar to normal class with these differences
  1. Contains only static members means all the methods and members must be static
  2. Cannot be instantiated by using new keyword
  3. By default it is sealed class and therefore cannot be inherited.
  4. It can have default constructor or
  5. Can have only one constructor without any parameter
  6. Access modifiers are not allowed on static constructors
  7. Cannot have instantiate constructors
  8. Methods can be called by using class name dot (.) method name.
What is a static Method?
Static method are similar to regular (instantiate) method, but they can be accessed directly by using the class name rather than the instance of the class, it will give error if we will try to access them with class instance, see it with this example:
  1. public class Sample
  2. {
  3.     public void DisplayInst()
  4.     {
  5.         Console.WriteLine("I am a instance method");
  6.     }
  7.     public void DisplayStatic()
  8.     {
  9.         Console.WriteLine("I am a static method");
  10.     }
  11. }
Call these two methods with instance and directly, see this
  1. var obj = new Sample();
  2. obj.DisplayInst();  // I am a instance method
  3. obj.DisplayStatic(); // Wrong, it cannot be called
  4. // Let’s try to call them directly
  5. Sample.DisplayInst();  // Wrong, it cannot be called
  6. Sample.DisplayStatic(); // I am a static method
Can we have static as well as instantiate constructor in a class?
  1. Yes, it can be in a normal instantiate class
  2. Any number of instantiate constructors
  3. With zero to any number of parameters
  4. Can have only one static constructors
  5. Static constructor cannot have any parameter
  6. Static constructor are mostly used to initialize some values
We will create a simple Car class with different constructors and a static constructor to understand the feature, let’s create a class with two instantiate constructor, one static constructor and two Detail methods
  1. public class Car
  2. {        
  3.     String _color = "White";
  4.     static decimal _price = 25000;
  5.     static Decimal _discount = 100;
  6.     public Car()
  7.     {
  8.     }
  9.     public Car(String color)
  10.     {
  11.         this._color = color;
  12.         _discount = 500;
  13.     }
  14.     static Car()
  15.     {
  16.         _discount = 1000;
  17.     }
  18.     public String Detail()
  19.     {
  20.         return String.Format("Price: {0:C} and Color: {1} "
  21.                                 , _price - _discount, _color);
  22.     }
  23.     public static String Detail(String color)
  24.     {
  25.         return String.Format("Price: {0:C} and Color: {1} "
  26.                                 , _price - _discount, color);
  27.     }
  28. }
It is valid and working class which has both types of constructors and methods, if you can see there is a normal constructor without any parameter and one static constructor without any parameter, because static constructor cannot have any parameter. Let's try to execute them one by one
  1. var car = new Car(); car.Detail();
    • Output: Price: $25,000 and Color: White
  2. var car = new Car(“Black”); car.Detail();
    • Output: Price: $24,500 and Color: Black
    • One parameter constructor is called and assign the discount $500
  3. Car.Detail(“Red”);
    • Output: Price: $24,000 and Color: Red
    • When we will call Detail method, constructor will be called before executing the method.
Try to add a new constructor like this and you will get following error
public static Car(Int32 color) { } 
  1. a static constructor must be parameterless
  2. access modifiers are not allowed on static constructors
Conclusion:
  1. Easy to use
  2. No need to create instance before calling the methods
  3. Cannot have more than one constructor
  4. Constructor cannot have any parameter
  5. Access modifier cannot be use with constructor
  6. Constructor is called before calling any method internally
  7. Cannot be instantiated
  8. Cannot be inherited because by default it is sealed

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...