views:

520

answers:

2

Hello, I have problem with class design.

I have core class for my game objects. While drawing I need to retrieve position from the object. Unfortunately object is seen as it's base type so the position is not retrieved from derived class but from it's parent. Defining field as virtual would fix my problem, but it's impossible :(. How can I design class schema to avoid this problem?

Simple example of what's going on:

class BaseClass { public Vector2 position = new Vector2(){X=0,Y=0}; }
class Class:BaseClass { public new Vector2 position = new Vector2(){X=10,Y=10}; }

BaseClass c = new Class();
// c.position.X is now 0
+1  A: 
Reed Copsey
+1  A: 
  • The new keyword indicates to hide the symbol of the same name defined in the base class.
  • public fields are considered a "smell" in C#

Solution: use properties and override the property in the derived class:

class BaseClass {
    public virtual Vector2 Position {
        get { return new Vector2(){X=0,Y=0}; }
    }
}

class Class : BaseClass {
    public override Vector2 Position {
        get { return new Vector2(){X=10,Y=10}; }
    }
}

You can use a backing field to store the instances of Vector2.

Alternatively, you can let the base class handle the position and just pass an initial value:

class BaseClass {
    private Vector2 _position;
    public BaseClass() {
        _position = new Vector2(){X=0,Y=0};
    }
    protected BaseClass(Vector2 initialPosition) {
        _position = initialPosition;
    }
    public Vector2 Position {
        get { return _position; }
        set { _position = value; }
    }
}

class Class : BaseClass {
    public Class() : base(new Vector2(){X=10,Y=10}) {
    }
}
dtb