mrblah
mrblah

Reputation: 103497

do you need the ref or out parameter?

I am passing a instance of a class to a method, and that method will modify the instance.

Do I need to use the out or ref keyword since this is a class I am passing?

This is what I want to do:

public void Blah()
{
   Blah b = Dao.GetBlah(23);

   SomeService.ModifyXml(b);    // do I need to use out or ref here?

   Dao.SaveXml(b.xml);

}

Upvotes: 2

Views: 659

Answers (5)

JMD
JMD

Reputation: 7377

If the reference b is not being modified, and only b's properties are being modified then you need neither ref nor out. Both of those would be approriate only if the reference itself was being modified.

I've expanded your sample code a bit to include usage for ref, out, and neither:

http://pastebin.ca/1749793

[Snip]

public void Run()
{
    Blah b = Dao.GetBlah(23);

    SomeService.ModifyXml(b);    // do I need to use out or ref here?
    Dao.SaveXml(b.Xml);

    SomeService.SubstituteNew(out b);
    Dao.SaveXml(b.Xml);

    SomeService.ReadThenReplace(ref b);
    Dao.SaveXml(b.Xml);
}

The rest of the code is in that PasteBin.

Upvotes: 5

Eric Lippert
Eric Lippert

Reputation: 660004

The right way to think about this is: use ref/out when you want to create an alias to a variable. That is, when you say:

void M(ref int x) { x = 10; }
...
int q = 123;
M(ref q);

what you are saying is "x is another name for the variable q". Any changes to the contents of x change q, and any changes to the contents of q change x, because x and q are just two names for the exact same storage location.

Notice that this is completely different from two variables referring to the same object:

object y = "hello";
object z = y;

Here we have two variables, each variable has one name, each variable refers to one object, and the two variables both refer to the same object. With the previous example, we have only one variable with two names.

Is that clear?

Upvotes: 14

Joe
Joe

Reputation: 16831

An easy way to check is with intellisense: hover your mouse over ModifyXml and if the parameter in the method signature contains out, such as ModifyXml( out Blah blah ), then you need the out keyword. Same goes for ref.

Upvotes: 0

David M
David M

Reputation: 72850

No you don't. The default behaviour when passing an instance of a reference type as a parameter is to pass its reference by value. This means you can alter the current instance, but not swap it out for another different instance. If this is what you mean by "modify the instance", then you you don't need ref or out.

Upvotes: 1

Samuel Neff
Samuel Neff

Reputation: 74909

No, you do not want ref or out here. You want to use ref when the method will change the object that the parameter points to. You want to use out when the method will always specify a new object for the parameter to point to.

Upvotes: 1

Related Questions