Reputation: 21
Let's say that I have an object of type A
at index 5 of array items
and I want to change it to be a new object of type B
.
If I had a reference to the array, I could just do items[5] = new B();
to change the item.
However, let's suppose that I only had the object at items[5]
and not the reference to the array, and it's stored in a variable item
. If I just do item = new B();
, the change will not be reflected in the array, because only that variable will be changed.
Is it possible to change that item in such a way that the change will be reflected in the array, such that items[5]
will contain that new item of type B
?
Preferably something simple without the use of delegates or lambdas or the like because it is somewhat performance-critical.
Upvotes: 2
Views: 105
Reputation: 6766
I believe in this case you should use ref.
Demonstrating example:
public class Program
{
public static void Main()
{
var list = new List<Sample>();
list.Add(new SampleDerived(){ Age=2, DAge = 5 });
list.Add(new SampleDerived(){ Age=3, DAge = 5 });
list.Add(new SampleDerived(){ Age=4, DAge = 5 });
list.Add(new SampleDerived(){ Age=5, DAge = 5 });
list.Add(new SampleDerived(){ Age=6, DAge = 5 });
var list2 = list.ToArray();
Process(ref list2[2]);
Console.WriteLine(list2[2].Age); // will print 10 not 4
}
public static void Process(ref Sample s)
{
s = new Sample(){Age=10};
}
}
public class Sample
{
public int Age {get; set;}
}
public class SampleDerived : Sample
{
public int DAge {get; set;}
}
Dot net fiddler is here.
Upvotes: 1