Static Classes

static class is a class that contains only static members and cannot be instantiated.  You declare a class as static using the static keyword.

A static class:

  • Can only have static members (can't contain instance members)
  • Cannot be instantiated
  • Cannot serve as the type of a variable
  • Cannot serve as a parameter type
  • Cannot inherit from another class
  • Cannot serve as a parent of another class
Example :

namespace ConsoleApplication1
{
    class Program
    {               
        static void Main(string[] args)
        {
            Employee e1 = new Employee("keshav", 23);
            Employee e2 = new Employee("Raj", 24);
            EmployeeMethods.SpeakALot(e1);
            Console.WriteLine(EmployeeMethods.MarriedName(e1,e2));
            Console.ReadLine();
        }        
    }

    public static class EmployeeMethods
    {
        private static int NumSpeak = 5;

        public static void SpeakALot(Employee d)
        {
            for (int i = 1; i <= NumSpeak; i++)
            {
                d.EmployeeSpeak();
            }
        }

        public static string MarriedName(Employee d1, Employee d2)
        {
            return d1.Name + d2.Name;
        }
    }

    
    public partial class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        
        public Employee(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public void EmployeeSpeak()
        {
            Console.WriteLine("Hello");
        }
    }
}

-----------------------------------------------------------------------------------
Ebook Download
View all
Learn
View all