2

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Process uses list2[2] as an argument. One of the requirements is that I only have access to the object and not the array or the item's index in the array.
How exactly did you get that object? Is it a reference to the object in the array or a copy of the object in the array?
@VeselinVasilev is is called pass by reference look at MSDN link for more detail.
It is a reference to the object in the array. That is, it's a different variable but points to the object in the array.
@NathanaëlRadomír I think it is not possible then. you will have to maintain some reference to the object before method call. You may go with pointer (unsafe code) but I would not recommend it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.