tags:

views:

57

answers:

1

I am trying to achieve something like the following:

class Foo
{
    public virtual int Number { get; set; }

    public Foo(int n)
    {
        Number = n;  //Virtual member call in constructor
    }

    public void Do() {
        Console.WriteLine(Number);
    }

}

class Bar : Foo
{
    public override int Number
    {
        get
        {
            return x.Val;
        }
        set
        {
            x.Val = value;
        }
    }

    Bar(int n) : base(n)
    {
        X x = new X();
        x.Val = n;
    }

    public void F() {
        x.Something();  //changes x.Val
    }
}

The reason I am doing this is because I need to propagate the call to Do when called from a variable of type Bar.

Now, I can have objects that either inherit from Foo or Bar, thus Number needs to be the way it is now, ie directly expose the Val property of x. This is because I need to allow for the following code:

Bar b = new Bar(5);
b.F(); //changes the value of Val in x
b.Do(); //Needs to print the correct, modified value

The problem here is obviously in Foo, when assigning n to Number (Virtual member call in constructor) since x from the subclass would not have been initialized yet.


What do you think is a better way to structure such a design?

I can't use this current code because I am calling a virtual member from the constructor, which causes the Object Reference not set to an Instance of an Object exception since x in Number from Bar would not have been yet initialized.

A: 

My favorite quote:

Favor composition over inheritance

I would separate underlying data from operations:

interface IMyNumber
{
   int Number { get; set; }

   void Something();
}

class MyNumber : IMyNumber
{
    public int Number { get; set; }

    public MyNumber(int n)
    {
        Number = n;
    }

    void Something() {... }
}

class MyBoxedNumber : IMyNumber
{ 
    int Number { get { ... } set {... } }

    void Something() {... }
}

class Bar
{
    private IMyNumber_foo;

    Bar(IMyNumber foo)
    {
        _foo = foo;
    }

    public void F() {
        _foo.Something();  //changes x.Val
    }

    public void Do() {
        Console.WriteLine(...)
    }
}
onof