By 22/07/2015 8 Comments

Instance Variables In C#

  • The instance variables 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.).
  • These variables belong with an object of a class and can also be called object variables or fields.
  • Every object of a class has its own copy of each instance variables. Or when we create multiple objects of a same class type than multiple copies of each instance variables are created and assign to each object. These copies make different one objects from other.
  • An object of a class must be created in order to access instance fields/variables because instance fields need an object reference variable for access.


using System;
namespace csharpBasic

    // Declare a class MarkSheet.
    class MarkSheet
        // Following is the declaration of two string type instance variables / fields.
        public string StudentName;
        public string StudentAddress;

    }  // End class definition scope.

    class Program
        // Static main method void type declaration.
        static void Main(string[] args)
            // First Marksheet object is being created.
            MarkSheet markSheetOne = new MarkSheet();

            // Second Marksheet object is being created.
            MarkSheet markSheetTwo = new MarkSheet();

            /* Following statements initialize the instance variables of 
               first object with different values.
            markSheetOne.StudentName = "abc";
            markSheetOne.StudentAddress = "xyz";

            Console.WriteLine("Marksheet 1 Student name: {0}", markSheetOne.StudentName);
            Console.WriteLine("Marksheet 1 Student address: {0}", markSheetOne.StudentAddress);

            /* Following statements initialize the instance variables of second object with different values. 
               NOTICE: in following statements we initialize second object’s instance fields with different values, 
               so these both objects are now different from each other’s.
            markSheetTwo.StudentName = "def";
            markSheetTwo.StudentAddress = "ghi";


            Console.WriteLine("Marksheet 2 Student name: {0}", markSheetTwo.StudentName);
            Console.WriteLine("Marksheet 2 Student address: {0}", markSheetTwo.StudentAddress);

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 .