C# program to demonstrate the static class

Here, we are going to demonstrate the static class in C#.
Submitted by Nidhi, on November 08, 2020

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.

Program:

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 »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.