atair
atair

Reputation: 65

direct access to base class variables / objects c#

public class myWorld
{
    public int data;
    public void ChangeData()
    {
        data = 10;
    }
}

public class myRobot : myWorld
{
    public void robotChangesData()
    {
        //how can i make the robot change the data in world?
    }
}

i understand (more or less) that this should not be done this way, and has been asked a thousand times, as every change should be through methods - but:

if we stay with the world and robot example, later on i want to have a method for the robot like: robot.MoveBox(25) where the robot has to have access to the world, an object box, and make updates to the drawing objects (meshes, shapes etc.) The only thing i can come up with now, is to pass for every method of the robot (like movebox, or robotChangesData) the whole world + box + drawing stuff as a 'ref' and he can change it then.. but the every method would look something like robot.MoveBox(25, ref myworldObject, ref myworldBoxes,ref etc etc)

Is this really the right way to go? or did i miss something important?

Upvotes: 3

Views: 22432

Answers (2)

bas
bas

Reputation: 14902

Maybe an example helps:

Your robot base class

public class RobotBase
{
    protected int data;

    // Reference to the world
    protected World _world;

    public RobotBase(World world)
    {
        _world = world;
    }

    public void ChangeData()
    {
        data = 10;
    }
}

Your robot class:

public class Robot : RobotBase
{
    public Robot(World world) : base(world)
    {}

    public void RobotChangesData()
    {
        //Change data in base
        data = 20;

        // Change data in world, the object is passed by reference, no need for further "ref" declarations
        _world.Terminate();
    }
}

Your world class:

public class World
{
    public void Terminate() 
    {
       // terminate world! noooess!
    }
}

Upvotes: 6

Srikant Krishna
Srikant Krishna

Reputation: 881

You don't to pass it as a ref.

Create a class/object representation for your model, and only pass that in as a paramter to your robot.

Exposed methods should correspond to varoables that can he changed.

Don't use refs and outs for each world/model state variable.

Upvotes: 0

Related Questions