Monday, November 12, 2018

Objects (Reference types) are also passed by value.


We will recall two concepts 'Call by Value' and 'Call by Reference' in context of a method call.

Call By Value : when we call a method by passing any value type, a copy of value type created inside of method so, any change to the variable's value inside the method, is local to that method, it will not change value of variable passed to that method. for example :

 Output :


In above example we saw, if we want to change value of  any 'value type' from another method we need to pass variable's reference to the method, otherwise all the changes to that variable will be local (inside) to that method.

Now, Question is about to 'Reference Type', Reference types are 'Passed by Value' or 'Passed by Reference' ?
You may not believe, if I will say reference types are also 'Passed by Value' because generally we saw when we pass any object to any method (say M1), any change to object inside M1() will reflect to caller. for example :



In the above example, after ChangeObject() method call, properties of Customer object has been changes. so, we can say objects are passed by reference.
No, It's not correct answer, objects are also 'Passed by Value'. See below example :




No comments:

Post a Comment

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...