Thursday, 14 February 2013

Working with Objects in CSharp

If required the object of a class can be assigned to the variable of the same class and initialized it, so that the variable becomes reference of the class but references of a class will not have separate memory allocation. They will be provided with access to the memory of object and reference will be consuming the same memory. To test this rewrite the code under Main method of class first as following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpConsole
{
    class First
    {
        int x = 100;
        static void Main()
        {
            First f1 = new First(); // f1 is a object
            First f2;              // f2 is a reference
            f2 = f1;
            Console.WriteLine(f1.x + "   "+ f2.x);
            f1.x=300;
            Console.WriteLine(f1.x + "   "+ f2.x);
            f1.x = 500;
            Console.WriteLine(f1.x + "   " + f2.x);
            Console.ReadLine();
        }
     }
}
/* In the above case, as the object and reference were consuming the same memory
 * any modifications that are performed on the members through 1 reflects on the
 * other also*/

No comments:

Post a Comment