C# - Static Class Example

In this example, we will learn about the static class with the help of example using C# program?
Submitted by Nidhi, on November 08, 2020 [Last updated : March 22, 2023]

Static Class

Here, we will create a static class that contains static members, here, we calculate the sum of two integer data members and print the calculated sum on the console screen.

Points related static class

  1. We cannot create the instance of a static class.
  2. The static class contains only static members.
  3. The static class is sealed class then it cannot be inherited.

C# program to demonstrate the example of static class

The source code to demonstrate the static class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to demonstrate the static class in C#

using System;

public static class Sample
{
    static int num1;
    static int num2;

    public static void Set(int n1, int n2)
    {
        num1 = n1;
        num2 = n2;
    }

    public static int GetSum()
    {
        return (num1 + num2);
    }
}

class Test
{
    static void Main(string[] args)
    {
        Sample.Set(10, 20);

        Console.WriteLine("Sum: " + Sample.GetSum()); 
    }
}

Output

Sum: 30
Press any key to continue . . .

Explanation

In the above program, we created a static class Sample that contains two static data member num1 and num2. The Sample class also contains two static methods Set() and GetNum().

The Set() method is used to set the values of data members. The GetSum() method is used to return the sum of data members.

Now look to the Test class that contains the Main() method. The Main() method is the entry point for the program.

Sample.Set(10, 20);
Console.WriteLine("Sum: " + Sample.GetSum()); 

In the above code, we set the data members of the Sample class using the Set() method, and then get the sum of data members using the GetSum() method that will be printed on the console screen.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.