Understanding the Object Oriented Programming

In .net the object plays role everywhere even if you directly code or do not object has its existence.
I have small program which was Interview Question at Microsoft.
C# code and understand the life of object.

Open Visual Studio -> New Project->Select c# and then Select Console Application

Name project – ObjectLifeCycle

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectLifeCycle
{
    public class log
    {
        public Int32 i;

        public void TestA(log obj)
        {
            obj.i = 100;
        }

        public void TestB(log test)
        {
            test = new log();
            test.i = 1000;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            log o = new log();
            o.i = 10;
            Console.WriteLine(o.i.ToString());

            o.TestA(o);
            Console.WriteLine(o.i.ToString());

            o.TestB(o);
            Console.WriteLine(o.i.ToString());          
            
        }
    }
}

 

You can directly paste this code in your .cs file and execute the code , you should see output as followed
10
100
100

So the object of class log which has only one variable in it and methods which has argument passed as its own object is having different scope in different assignment.

In Main Method object is initialized with values first time so first writeline statement gives 10.
Second method call TestA with object o is passed. Inside the method their is just reassign of value to int as 100 so the value 10 is replaced to 100 for object o which is still having same reference.

Third method call TestB in which again object o is passed which had value of int as 100. Now inside method new object initialization happens that means new object o for which int value is 1000.
Now you must be wondering third value is not 1000, this is because TestB created new object with new memory allocation. So test object scope finished ones it came out of the method. Since the Writeline method is calling value available in object o it has given 100.

Lets do one more change on line 35

o.i = o.TestB(o);

 


In above case what is happening is we are copying return value of int from TestB method and assign it to object o.i int value. of course TestB return type has to be changed from void to int.

It should return
10
100
1000

For more details http://msdn.microsoft.com/en-us/library/fa0ab757%28v=vs.100%29.aspx

Happy programming….

Number of View :704
  1. No comments yet.

SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache