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?
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, withoutref
keyword that is not possible.Consider the following example:
Output would be:
When you see
ref object
that means, argument has to beobject
type.You can read in documentation:
In C#, the default mechanism of method arguments is Pass by Value. Hence if your are declaring a method like,
So, a new copy of the object is created, so the changes on the parameter will not affect the original object passed in.
But, when u pass the parameter by ref, it is Pass by Reference
Now, your are operating on the address on the originally passed object. Hence the changes u are making on the parameter inside the method will affect the original object.
passing a variable by ref allows the function to repoint that variable to another object, or indeed null: e.g.
Argument Passing ByVal: Describes passing arguments by value, which means the procedure cannot modify the variable itself.
Argument Passing ByRef: Describes passing arguments by reference, which means the procedure can modify the variable itself.