Does it make sense to pass a "reference type" to a method as a parameter with 'ref' key? [duplicate]
Possible Du开发者_运维技巧plicate:
C#: What is the use of “ref” for Reference-type variables?
Hi,
Does it make sense to pass a "reference type" to a method as a parameter with 'ref' key?
Or it is just nonsense as it is already a reference type but not a value type?
Thanks!
It lets you change the reference variable itself, in addition to the object it's pointing to.
It makes sense if you think you might make the variable point to a different object (or to null
) inside your method.
Otherwise, no.
When passing a reference type as ref, you are passing the reference as a reference, and this might make sense. It means that the method can replace the reference, if it wishes to:
public void CallRef()
{
string value = "Hello, world";
DoSomethingWithRef(ref value);
// Value is now "changed".
}
public void DoSomethingWithRef(ref string value)
{
value = "changed";
}
If makes a difference, because it allows the method to change the instance your variable is pointing to.
In other words, you use it when you want to make your variable point to a different instance of your reference type.
private static void WithoutRef(string s)
{
s = "abc";
}
private static void WithRef(ref string s)
{
s = "abc";
}
private static void Main()
{
string s = "123";
WithoutRef(s);
Console.WriteLine(s); // s remains "123"
WithRef(ref s);
Console.WriteLine(s); // s is now "abc"
}
ref in C# allows you to modify the actual variable.
Check out this question - What is the use of "ref" for reference-type variables in C#? - including this example
Foo foo = new Foo("1");
void Bar(ref Foo y)
{
y = new Foo("2");
}
Bar(ref foo);
// foo.Name == "2"
It's not nonsense. When you do that, you're passing the reference by reference.
Example:
class X
{
string y;
void AssignString(ref string s)
{
s = "something";
}
void Z()
{
AssignString(ref this.y};
}
}
It does if you want the incoming variable that is being passed in to have its pointer changed.
Consider the following code. What do you expect shall be the output from this program?
string s = "hello world";
Console.WriteLine(s);
foo(s);
Console.WriteLine(s);
bar(ref s);
Console.WriteLine(s);
void foo(string x)
{
x = "foo";
}
void bar(ref string x)
{
x = "bar";
}
The output is:
hello world
hello world
bar
When calling the method bar
, you're passing the reference to string s
by reference (instead of by value), which means that s
will then change at the call site.
精彩评论