Skip to content

#11 Static Class, Methods, Constructor, Fields

When you define a class, method constructor, or field as static it means that a thing will only have one instance of it and it can’t be instantiated. I.e you are taking away the ability to create or access it using an object.

Rules

  • Static classes can’t be instantiated.
  • If a class is declared as static then all its members must also be declared as static.
  • Static classes are sealed and hence can’t be inherited.
  • A static class remains in memory till the lifetime of the application.
using System;
public static class Staticclass
{
    public static int Value { get; set; }

    public static int getValue()
    {
        return Value;
    }
}

public class nonstaticclass
{
    public int Value { get; set; }

    public static void getValue()
    {
        Console.WriteLine("I cant access value property");
    }
}

class Program
{ 
    static void Main(string[] args)
    {
        //below object cretion will not work
        //Staticclass obj = new Staticclass();
        Staticclass.Value =10;
        Console.WriteLine(Staticclass.getValue());
        nonstaticclass obj = new nonstaticclass();
        obj.Value =10;
        
        //obj.getValue(); this will not work
        nonstaticclass.getValue();
        
        Console.ReadKey();
    }
}
Published inC#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *