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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…