C # object memory / understanding

Therefore, I cannot find a specific answer to this question in a way that is very digestible. So please tell me if this is a stupid question.

If I instantiate an object like:

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

      

And then in another class I:

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


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

      

I understand that both subShip and mainShip now refer to the same object in the "heap" or in memory. Is that correct and also ... is it a bad idea? I am very beginner (1-2 weeks only) so any guidance would be much appreciated.

Thank! -Brandon

+3


source to share


2 answers


I understand that both subShip and mainShip now refer to the same object in the "heap" or in memory.

If PlayerShip

is class

, then yes, you will have two links to the same object.

If it PlayerShip

is struct

no, the assignment will create a copy and use that copy.



it is a bad idea

This is neither bad nor good, it is just a tool.

+7


source


Let's assume Movehip is a class. Then you have different execution states:

public class RandomEncounters
{
    PlayerShip subShip = new PlayerShip();    //a

      

You now have different links. One reference is from a static object mainShip

and the other is from the newly created object subShip

. But after calling the method:

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

      



You refer to a static object mainShip

, so both subShip

, and mainShip

refer to the same object.

It is a bad idea?

What exactly? Reference to another object? No, this is not a bad idea and has been used quite often.

But it is not recommended to assign your object directly (I am marked with line a) if you never use the first assigned object (I don't see any use, perhaps you used subShip

already before execution PlayEncounter()

, then it will make sense again). But if you haven't used it, you are directly overwriting the old link, it is just a waste of memory space and runtime. It doesn't make a big difference, but you also can't call it a good idea.

0


source







All Articles