Reputation: 2092
I am just testing something and I’m wondering whether there is any benefit for using ref. So in the code below I have two methods both accept observablecollection of customer, one with a ref one without. Both do exactly the same (update the original list). So what is the advantage of using ref?
ObservableCollection<Customer> customers;
public MainWindow()
{
InitializeComponent();
customers = new ObservableCollection<Customer>()
{
new Customer () { Id = 1, Name="Batman"},
new Customer () { Id = 2, Name="Spiderman"},
};
AddCutomer(customers);
AddCutomer(ref customers);
}
public void AddCutomer(ObservableCollection<Customer> customers)
{
customers.Add(new Customer() { Id = 3, Name = "Superman" });
}
public void AddCutomer( ref ObservableCollection<Customer> customers)
{
customers.Add(new Customer() { Id = 3, Name = "Superman" });
}
If I use an int, then again it does not matter whether I use keyword ref or not, it changes the original value. However string behaves different depending on whether I use ref or not.
Kind Regards
Upvotes: 0
Views: 779
Reputation: 4197
Using ref
for Reference types allow you to do modify the reference itself, as oppose to the value it's pointing to.
Using your example, if you create a new ObservableCollection and assign it to the customers
variable within your AddCustomer
function, then the customers variable in the calling function MainWindow
will now point to this new collection. I.e. the old collection will be lost.
Upvotes: 1
Reputation: 1019
In this context: none at all. Ref passes a reference to the variable containing a reference to the instance, rather than copying the reference to the instance.
static void Main()
{
int i = 1;
int j = 2;
Foo(ref i);
Console.WriteLine(i); // Should print 10
Bar(j);
Console.WriteLine(j); // Should print 2
}
static void Foo(ref int value)
{
value = 10;
}
static void Bar(int value)
{
value = 15;
}
Foo
will change the value of i
but Bar will not change the value of j
.
Exact same behavior for reference types.
ref
is most useful for structs. In most other cases out
is preferred since it guarantees that the value is changed.
Upvotes: 1