Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'ref' keyword in C# [duplicate]

Tags:

c#

.net

Possible Duplicates:
Why use ref keyword when passing an Object?
When to pass ref keyword in

What is the correct usage of the 'ref' keyword in C#. I believe there has been plenty of discussion threads on this, but what is not clear to me is:

  1. Is the ref keyword required if you are passing in a reference object? I mean when you create an object in the heap, is it not always passed by reference. Does this have to be explicitly marked as a ref?
like image 958
Saibal Avatar asked Jan 27 '11 04:01

Saibal


2 Answers

Using ref means that the reference is passed to the function.

The default behaviour is that the function receives a new reference to the same object. This means if you change the value of the reference (e.g. set it to a new object) then you are no longer pointing to the original, source object. When you pass using ref then changing the value of the reference changes the source reference - because they are the same thing.

Consider this:

public class Thing
{
    public string Property {get;set;}
}

public static void Go(Thing thing)
{
    thing = new Thing();
    thing.Property = "Changed";
}

public static void Go(ref Thing thing)
{
    thing = new Thing();
    thing.Property = "Changed";
}

Then if you run

var g = new Thing();

// this will not alter g
Go(g);

// this *will* alter g
Go(ref g);
like image 179
Kirk Broadhurst Avatar answered Oct 11 '22 18:10

Kirk Broadhurst


There is a lot of confusing misinformation in the answers here. The easiest way to understand this is to abandon the idea that "ref" means "by reference". A better way to think about it is that "ref" means "I want this formal parameter on the callee side to be an alias for a particular variable on the caller side".

When you say

void M(ref int y) { y = 123; }
...
int x = 456;
M(ref x);

that is saying "during the call to M, the formal parameter y on the callee side is another name for the variable x on the caller side". Assigning 123 to y is exactly the same as assigning 123 to x because they are the same variable, a variable with two names.

That's all. Don't think about reference types or value types or whatever, don't think about passing by reference or passing by value. All "ref" means is "temporarily make a second name for this variable".

like image 35
Eric Lippert Avatar answered Oct 11 '22 17:10

Eric Lippert