I wonder what the difference is between the following methods with regards to how the object parameter is referenced:
public void DoSomething(object parameter){}
and
public void DoSomething(ref object parameter){}
Should I use ref object parameter
in cases where I want to change the reference to the object
not override the object in the same reference?
ref keyword is used when a called method has to update the passed parameter. out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way. out keyword is used to get data in uni-directional way.
What is the difference between the ref and out keywords? Variables passed to out specify that the parameter is an output parameter, while ref specifies that a variable may be passed to a function without being initialized.
Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference. By default parameters are passed to a method by value. By using these keywords (ref and out) we can pass a parameter by reference.
public void DoSomething(object parameter)
{
parameter = new Object(); // original object from the callee would be unaffected.
}
public void DoSomething(ref object parameter)
{
parameter = new Object(); // original object would be a new object
}
See the article: Parameter Passing in C# by Jon Skeet
In C#, Reference type object's address is passed by value, when the ref
keyword is used then the original object can be assigned a new object or null, without ref
keyword that is not possible.
Consider the following example:
class Program
{
static void Main(string[] args)
{
Object obj1 = new object();
obj1 = "Something";
DoSomething(obj1);
Console.WriteLine(obj1);
DoSomethingCreateNew(ref obj1);
Console.WriteLine(obj1);
DoSomethingAssignNull(ref obj1);
Console.WriteLine(obj1 == null);
Console.ReadLine();
}
public static void DoSomething(object parameter)
{
parameter = new Object(); // original object from the callee would be unaffected.
}
public static void DoSomethingCreateNew(ref object parameter)
{
parameter = new Object(); // original object would be a new object
}
public static void DoSomethingAssignNull(ref object parameter)
{
parameter = null; // original object would be a null
}
}
Output would be:
Something
System.Object
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With