reference parameters is only useful for valuetypes? for example if you have a method that passes in a class, the ref keyword is useless?
public class someclass
{
}
somefunction(ref someclass input)
{
}
reference parameters is only useful for valuetypes? for example if you have a method that passes in a class, the ref keyword is useless?
public class someclass
{
}
somefunction(ref someclass input)
{
}
You surely could use a ref parameter for a class type. For instance:
void MyClassFactory(ref MyClass newRef)
{
newRef = new MyClass();
}
MyClass someRef = null;
MyClassFactory(ref someRef);
// Now someRef is referencing a new MyClass object.
And notice that the above code would not work without the ref
keyword.
ref can be useful for reference types if you need to replace the object the function was given with a new object. For example:
class MyClass
{
}
class MyClass2 : MyClass
{
public MyClass2(MyClass original)
{
}
}
bool UpdateMyClass(ref MyClass input)
{
bool success = false;
if (input != null)
{
//Generate a new object with some additional functionality.
input = new MyClassWithSuperPowers(input);
success = true;
}
return success;
}
And of course, the most obvious use case is the string class.
void FormatString(ref string data)
{
data = DateTime.Now + data;
}
My understanding is this(and I hope someone corrects me if I'm wrong):
C# contains value types(allocated on the stack), and reference types(allocated on the heap).
However, all parameters are passed by value by default, which means if you call a function
myFunc(myClass param) { }
...
myClass myVar = new myClass();
myFunc(myVar);
//myVar will not be changed here
Then a cheap copy of myVar will be created and passed into myFunc.
If you pass the same parameter by using the 'ref' keyword, then a copy of myVar is not made, and instead a reference to myVar is passed in. Then any changes made to myVar inside myFunc would be reflected in myVar once myFunc returns.
myFunc(ref myClass param) { }
...
myClass myVar = new myClass();
myFunc(ref myVar);
//myVar might be changed here
I'm having trouble finding an article that actually talks about parameters and not just value vs. refernece types, but I think this is how it works.