Monday, July 23, 2007

call by value v/s call by ref

call by value functions are simple where in we pass the value to the function from where we call.
For ex.

public int Add(int x, int y) //call by value
{
x = x + y;
return x;
}

is a call by value function since we are only passing the values. i.e,
int x = 25;
int y = 20;
int z = Add(x,y);
definitely z = 45 now but x = 25 . Let us see what will happen if we use call by reference,
syntax will be something like this:
public int Add(ref int x, int y)
{
x = x + y;
return x;
}

now for z = Add(ref x ,y);
z=45 but see the difference x also has 45 since we pass the reference.

Also learn about Delegates in C#

3 comments:

a said...

its great,cud u pls demonstrate it little more

Sachin Saini said...

I am not from .Net bachground but still asking a doubt from your code: Your function Add() returns "void" and how come 45 will be assigned in "z" through z=Add(x,y, because Add() won't return the result. is not it?

Nanju said...

Hi buddy , though little I just saw ur comment :).Thanks. Please check it now.