What's the difference between the 'ref' and 'out' keywords?
You: I need to pass an object so that it can be modified It looks like MyClass
would be a class
type, i.e. a reference type. In that case, the object you pass can be modified by the myFunction
even with no ref
/out
keyword. myFunction
will receive a new reference that points to the same object, and it can modify that same object as much as it wants. The difference the ref
keyword would make, would be that myFunction
received the same reference to the same object. That would be important only if myFunction
were to change the reference to point to another object.
回答1
ref
tells the compiler that the object is initialized before entering the function, while out
tells the compiler that the object will be initialized inside the function.
So while ref
is two-ways, out
is out-only.
回答2
The ref
modifier means that:
- The value is already set and
- The method can read and modify it.
The out
modifier means that:
- The Value isn't set and can't be read by the method until it is set. 就算在进入方法前,设置了值,也是无效的
- The method must set it before returning.
This answer most clearly and concisely简洁地 explains the restrictions that the compiler imposes when using the out keyword as opposed to the ref keyword.
Is using the 'ref' keyword for string parameters in methods good for performance in C#? [duplicate]
When I use this method, the compiler creates a copy of the text for the method, right?
No, it doesn't. string
is a reference type, and the compiler will create a new stack variable which points to the same string
represented at a given memory address. It won't copy the string.
When you use ref
on a reference type, there won't be a copy of the pointer to the string
created. It will simply pass the already created reference. This is useful only when you want to create an entirely new string
:
void Main()
{
string s = "hello";
M(s);
Console.WriteLine(s);
M(ref s);
Console.WriteLine(s);
}
public void M(string s)
{
s = "this won't change the original string";
}
public void M(ref string s)
{
s = "this will change the original string";
}
So is it good for performance using ref like this?
The performance gains won't be noticeable. What will happen is other developers getting confused as to why you used ref
to pass the string.