Sunday, June 7, 2015

Object Reference is Passed By VALUE

Hello Guys,

I am back. Don't you think that title looks confusing. We studied in college and schools that in Methods Objects are automatically passed by reference.

And here i am saying In Methods Object Reference is passed by VALUE.

Actually knowingly or unknowingly we are using it. It's our regular way of Programming.

Here i am making simple program please check it out and before checking output downside please i request you to guess the output.

using System;

namespace ObjectReferenceDemo
{
    class Person
    {
        public String Name { get; set; }
    }
}
using System;

namespace ObjectReferenceDemo
{
    class Program
    {
        static void Main()
        {
            Person objPerson = new Person() { Name = "abc" };
            Console.WriteLine("In Main :- {0}", objPerson.Name);
            Console.ReadLine();


            Initialize(objPerson);
            Console.WriteLine("After Initialize Method :- {0}", objPerson.Name);
            Console.ReadLine();

            MakeNull(objPerson);
            Console.WriteLine("After MakeNull Method :- {0}", objPerson.Name);
            Console.ReadLine();
        }

        static void Initialize(Person objPerson)
        {
            objPerson.Name = "xyz";
        }

        static void MakeNull(Person objPerson)
        {
            objPerson = null;
        }
    }
}

Now Please check all the following output.

1) First Readline :-











2) Second ReadLine :-











3) Last ReadLine :-











Wowww... Don't you think that according to JAVA or .NET we studied in college or schools that objects are automatically passed by reference... should throw NullPointerException.
  • When you pass object to methods you can change it's properties. But you can't replace complete object. Don't you think it's really different.
That's Because of "OBJECT REFERENCES ARE PASSED BY VALUE."

For more information about it you can check the following websites that i referred.

Passing Objects By Reference or Value in C#

Java is Pass-by-Value, Dammit!

Is Java “pass-by-reference” or “pass-by-value”?

Here i am also attaching my project for reference.

Download Project

Thank you guyz. Please check it. And waiting for your comments and replies.