Question

At assigning one field to another, does the C# just copy data over, or actually creates link? In this article there's an example of game engine structure. The coder there has components contain their parent. In C#, do they just contain the parent copy, or they refer to it?

Example code:

class World
{
    ...
    public void Update()
    {
        ...
        ent.OnAttach(this);
        ...
    }
    ...
}

class Entity
{
    ...
    public void OnAttach(World world)
    {
        world_ = world;
    }
    ...
}

Could the Entity object now access World object and have access to it's fields and methods, like in the artice? (or I misunderstood the code?)

Was it helpful?

Solution

Because your data type World is defined as a class and not a struct that means that when you assign a variable of that type, only a reference to the same data is copied.

In other wrods, whether you then use world.SomeProperty = something or world_.someProperty = something they will be editing the same object in memory.

If you change your data type to be a struct then the entire data structure will be copied and you will have two copies of the same data.

Regardless of how you defined your data, once you have a reference to the data you can then access its methods or properties. So, yes, once your Entity object has a reference to the world object it can access any methods or properties on it (as long as they are not private).

OTHER TIPS

It depends on the World type. If it's a reference type (a class), the copied reference will point to the same object and thus changing the object pointed by the new reference will affect the original object (no new object is created). This is the case in the posted sample. The field will simply refer to the same World object.

If the World type is a value type, it's copied (along with its contents) and will become an entirely distinct value, changing which will not affect the original.

As Entity & World are class (i.e. "reference types"), then they would just have references to each other. If one was a struct (i.e. a "value type"), then the enite thing would be copied.

You should have a look at passing by reference and passing by value. Your World object is a passed by reference, so you're passing a reference to a location in memory where the data this object contains resides.

Entity could now only access World object's public methods, properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top