Such type of class which is marked by static keyword is known as static class. All the members of static class must be static. We cannot declare non-static members inside static class. We can access members of static class by using Class name followed by access operator dot (.) followed by method name. One thing important that we cannot instantiate static class means to say we cannot create object of static class by using new keyword.
The following list provides the main feature of a static class
1) Contains only static members except for constants.
2) Cannot create objects of static class.
3) Is sealed class.
4) Can not contain instance constructor or non static constructor.
Creating static class
For creating static class we can use static keyword at the beginning of class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PropertyDemo
{
//use static keyword to create a static class.
static class Program
{
static Program()
{
Console.WriteLine("This is a static constructor.");
}
static string message;
static void disp()
{
Console.WriteLine(message);
}
public static void Main(string[] args)
{
Program.message = "Hello John..."; //Accessing static variables.
Program.disp(); //Accessing static methods.
Console.ReadLine();
}
}
}
Output:
This is a static constructor.
Hello John...
Anonymous User
11-Mar-2019Thank You.
Samuel Fernandes
20-Jul-2017Your words increase my knowledge for sure. Thanks