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?
开发者_StackOverflowThis 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);
}
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?
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.
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.
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
.
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
.
精彩评论