Wednesday, April 1, 2015

Static Classes in C#

A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

Why are static classes used?
Static keyword can be applied to
Class, field, method, properties, operator, event and constructors.
Static member belongs to the class and not to any object of the class.
They can be used without creating the instance of the class.
A static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed. 
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.
When to Use Static Classes in C#
Static methods are used when you will need to access a method from many different classes or forms, you wouldn't want to create an object every time you needed that method. and you certainly wouldn't want to retype or copy and paste the same method into every class you needed it in.

When to use them?
 
Well we can use them when we need to maintain information applicable to the entire class
Suppose we have a class StaticExample there we can have a static variable X and Y

static class StaticExample
{
    public static int X = 100;
    public static int Y = 200;
}

We can access static variable using 

StaticExample.X.ToString()
StaticExample.Y.ToString()

Example

We have static class Calculation , in that there are 4 Static method Addition, Subtraction, Multiplication, and Divide

static class Calculation
{
    public static int Addition(int x, int y)
    {
        return x + y;
    }
    public static int Subtract(int x, int y)
    {
        return x - y;
    }
    public static int Multiplication(int x, int y)
    {
        return x * y;
    }

    public static int Divide(int x, int y)
    {
        return x / y;
    }
}

We are called as below

Console.WriteLine("Addition =" + Calculation.Addition(20, 10));
Console.WriteLine("Subtract =" + Calculation.Subtract(20, 10));
Console.WriteLine("Multiplication =" + Calculation.Multiplication(20, 10));
Console.WriteLine("Divide =" + Calculation.Divide(20, 10));

Output
Addition = 30
Subtract = 10
Multiplication =200
Divide =2

No comments:

Post a Comment