By 22/07/2015 1 Comments

Static Variables In C#

  • Static variables in C#¬†are declared inside the class scope, if you will not assign any value to them by default it is initialized to its default values depends on its data types such as (0 for int, false for bool, null for string etc.).
  • We prefix to any variable type with keyword static to become it a static variable or field.
  • These variables belong with a class and can also be called class fields/variables.
  • Every object of a class has a same static variable, because there are no copy of a static variable is being made, all objects share that single static field.
  • A static variable must be accessed by its class name you do not need to create an object to access it.
  • Static variables are being called first than non-static or instance variables because static variables load into memory at compile time while instance variables loads into memory at run-time after object initialization.


using System;
namespace csharpBasic
    class MarkSheet
    { // Class scope is started.

        // Static fields/variables are declared.
        public static string StudentName;
        public static string StudentAddress;
        public static string Asp;
        public static double AspMarks;

    } // Class scope is ended.
    class Program
        // Static main method void type declaration.
        static void Main(string[] args)
            // Static variables are being initialiazed through a class name (MarkSheet) itself by .(dot) operator.
            MarkSheet.StudentName = "abc";
            MarkSheet.StudentAddress = "xyz";

            MarkSheet.Asp = "";
            MarkSheet.AspMarks = 80;

            // Static fields/variables are being printed.
            Console.WriteLine("Student name: {0}", MarkSheet.StudentName);
            Console.WriteLine("Student address: {0}", MarkSheet.StudentAddress);

            Console.WriteLine("Subject 1: {0}", MarkSheet.Asp);
            Console.WriteLine(" Marks: {0}", MarkSheet.AspMarks);
        The Output will be:
        Student name: abc
        Student address: xyz
        Subject 1: Marks: 80

Next Tutorial →

← Previous Tutorial

Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .