mathsicist mathsicist - 1 month ago 11
C# Question

Relating two objects of different classes

I'm not sure if the title is clear enough, but I don't know how to exactly describe my problem. I've created a class called Window and I'd like to create another one which would be related to attributes of the class. Let's call the new class Box.

So, we have an object myWindow of class Window, and an object myBox of class Box. I'd like to make sure that the size of myBox would never be bigger than the size of myWindow. As I see it (below):

Window myWindow = new Window()
myWindow.CreateBox()


The problem is that I don't know how to create a method, which would create an object of another class. Simultaneously, their attributes have to be constantly related to each other.

Please, advise me how to implement my idea.

Answer

something like this?

     public class Window
{
    private int _size { get; set; }
    public int Size
    {
        get
        {
            return _size;
        }
        set
        {
            if (value >= MyBox.Size)
                _size = value;
        }
    }
    public Box MyBox { get; set; }

    public Window(int myWindowSize, int myBoxSize)
    {
        if (myBoxSize > myWindowSize)
            throw new ArgumentException("box is bigger than window wah");

        Size = myWindowSize;
        MyBox = new Box(myBoxSize);
    }

    public void UpdateBoxSize(int newSize)
    {
        if (newSize > Size)
            throw new ArgumentException("box is bigger than window wah");
        MyBox.Size = newSize;
    }        
}

public class Box
{
    public int Size { get; set; }
    public Box(int myBoxSize)
    {
        Size = myBoxSize;
    }
}
Comments