Reputation: 973
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?
Upvotes: 4
Views: 258
Reputation: 147
In func2
you are creating a new instance of employee and assigning a value to it. Where as in func1
you are just modifying an already created instance and so the change is reflected back.
Upvotes: 0
Reputation: 499072
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.
Upvotes: 8
Reputation: 838376
When you call Func2
, it passes a reference by value. Assigning to e
inside the method does not change the value stored in emp
, it just assigns a different value to the local variable e
.
If you want to pass by reference use the ref
keyword.
Func2(ref emp);
private void Func2(ref Employee e)
{
// etc...
}
Upvotes: 2