Monday, November 23, 2015

Passing By Value Vs By Ref C#

A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable. If you want the called method to change the value of the parameter, you must pass it by reference, using the ref or out keyword. For simplicity, the following examples use ref.

Bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort

Class, delegate, dynamic, interface, object, string

C# Example
private void button1_Click(object sender, EventArgs e)
     int i = 100;

     PassByVal(i);   // Don't change original value
     button1.Text = i.ToString(); // OutPut is : 100

     PassByRef(ref i);   // Change original value
     button1.Text = i.ToString(); // OutPut is : 110

private void PassByRef(ref int i) { i += 10; }

private void PassByVal(int i) { i += 10; }

More Difference

Value Type
Reference Type
They are stored on stack
They are stored on heap
Contains actual value
Contains reference to a value
Cannot contain null values. However this can be achieved by nullable types
Can contain null values.
Value type is popped on its own from stack when they go out of scope.
Required garbage collector to free memory.
Memory is allocated at compile time
 Memory is allocated at run time

1 comment:

Haritha said...

Wonderful article, very useful and well explanation. Thanks a lot for offering this unique post with us. I really enjoyed by reading your blog post.

Hadoop Training in Chennai