I have used ref in the following way. So when a new object is created in the 5th method does access go all the way to the original emp in the main method and create a new object there?
If yes, is there a way that I implement the same functionality without so many iterations i.e., it should create a new object in the 5th method itself and the change should be reflected in the main methods' emp too?
public static void Main(string[] args)
{
Employee emp=new Employee();
emp.id=10;
Program p=new Program();
p.Method1(ref emp);
Console.WriteLine(emp.id);
Console.ReadKey();
}
public void Method1(ref Employee emp)
{
Method2(ref emp);
}
public void Method2(ref Employee emp)
{
Method3(ref emp);
}
public void Method3(ref Employee emp)
{
Method4(ref emp);
}
public void Method4(ref Employee emp)
{
Method5(ref emp);
}
public void Method5(ref Employee emp)
{
emp=new Employee();
emp.id=20;
}
does access goes all the way to the original emp in the main method and create a new object there
It doesn't create an object there, however it overwrites the reference to that object, it creates the object where it creates the object:
if yes is there a way that i implement the same functionality without so many iterations
What iterations? After all you did all the passing around.
it should create a new object in the 5th method itself and the change should be reflected in the main methods' emp too?
It's already doing that, with the exception that it doesn't change the original employee, it overwrites the location of it.
Console.WriteLine(emp.id);
// writes 20
Imagine for a second that you have made a pie and put it in a container.
Then Joe decides to make his own pie and put it in the container, your original pie disappears into the ether.
At that point there is no original object, the container now contains the new pie.
When you pass an object by reference, you are passing a reference that points to data stored in memory. If someone chooses to overwrite that reference then that's it, everyone with that reference gets the new overwritten one.
At this point now you need to do some research and read the documentation, ask your teacher or your friends, do what ever it is you need to do. However, asking this type of question is redundant, by the time you write a program you would have spent 15 years asking basic questions that you can figure out by reading.
Please start here:
When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The effect of passing by reference is that any change to the argument in the called method is reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refers to the new object when the method returns.