Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# memory/object understanding

Tags:

c#

If I instantiate an object like:

public class Program
{
    public static PlayerShip mainShip = new PlayerShip(); 
}

And then in another class I do:

public class RandomEncounters
{
    var subShip = new PlayerShip();

    public void PlayEncounter()
    {
        subShip = Program.mainShip;
    }
}

My understanding is that both subShip and mainShip are now referencing the same object in the 'heap' or memory. Is this correct, and also, is this a bad idea?

like image 209
Icywata Avatar asked Feb 04 '23 16:02

Icywata


1 Answers

My understanding is that both subShip and mainShip are now referencing the same object in the 'heap' or memory.

If PlayerShip is a class then yes, you will have two references for the same object.

If PlayerShip is a struct then no, assignment will a create a copy and will use that copy.

is this a bad idea

That's neither bad nor good, that's just a tool.

like image 180
Lanorkin Avatar answered Feb 07 '23 04:02

Lanorkin