Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain the output of program below?

Tags:

c#

oop

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        a.print();

    }
}

class Employee
{
    public string Name { get; set; }
}

class A
{
    public void print()
    {
        Employee emp = new Employee { Name = "1" };
        Func2(emp);

        Console.WriteLine(emp.Name);
        Console.ReadLine();
    }

    private void Func2(Employee e)
    {
        Employee e2 = new Employee { Name = "3" };
        e = e2;

    }

}

After running the Above program, I got "1" as answer, which I'm not able to understand HOW? Can anyone explain, the answer according to me should be "3" -Thanks

But when I call Func1 method which is defined below:-

private void Func1(Employee e)
{
    e.Name = "2";
}

I get "2" as answer. Now if e was passed as Value type then how come it's giving me "2" as answer?

like image 218
Deepak Sharma Avatar asked Dec 28 '22 01:12

Deepak Sharma


1 Answers

Here is the bit that is getting you regarding Func2:

private void Func2(Employee e)
{
    Employee e2 = new Employee { Name = "3" };
    e = e2;
}

Employee is a reference type (a class), but the reference itself is passed by value - it is a copy of the reference.

You are then assigning to this copy a new reference, but the original reference (that was copied from) did not change. Hence, you are getting a 1.

If you pass the reference itself by reference, you can modify it:

private void Func2(ref Employee e)
{
    Employee e2 = new Employee { Name = "3" };
    e = e2;
}

The above will produce 3, as you expected.


Update, regarding your added Func1:

The reference is a copy, but is still pointing to the same object - you are changing the state of this object (setting the Name property), not the underlying object reference itself.

like image 190
Oded Avatar answered Dec 30 '22 11:12

Oded