Snaggly
Snaggly

Reputation: 13

Inherited Classes from Abstract Class field mysteriously overwritten

My problem is once the program reaches MyMethod() once, it sets LocalField and InheritedProperty as the same one pointer, meaning whenever InheritedProperty changes LocalField does automatically too.

class Inherited : AbstractClass
{
    protected override void MyMethod()
    {
        LocalField = InheritedProperty;
    }

    public void MyNewMethod()
    {
        //Is the new Array different?
        //Do something
    }

    public long[] LocalField;

    protected override long[] InheritedProperty => RetrtieveNewArray;
}

Is it possible to someone make my LocalField a new field independent from InheritedProperty?

Upvotes: 0

Views: 52

Answers (1)

Martin Liversage
Martin Liversage

Reputation: 106906

You can clone the array:

LocalField = (long[]) InheritedProperty.Clone();

This will create an independent copy of the original array.

In your case the array element type is a value type (long) which means that cloning will copy all the numbers. However, if you do the same with an array containing references you will only get a "shallow" copy meaning that the references in the cloned array will reference the same objects as the references in the original array. This is not something relevant to the code in your question but something that you should be aware of when cloning arrays in general.

Upvotes: 1

Related Questions