C# How/Possible to add new property to existing class dynamically or with class extension?

179 views Asked by At

So, I have an object, and it would be very beneficial if I could include a reference to another object within this object upon its creation.

In this specific circumstance the class that is being used is: Windows.UI.Xaml.Shapes.Rectangle

So the way I was trying to do this was the following, I do not have that much knowledge about C#, been studying it now for 3 months. So it is very likely the way I am trying to do this is far from optimal. But I hope that the following examples will display what I am trying to do.

The first way was to simply try adding the property dynamically:

var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
object obj = new object();
rectangle._obj = obj;

The second way was to try and extend the class, and then using my own constructor.

class My_Rectangle : Windows.UI.Xaml.Shapes.Rectangle {
    private object _obj;
    public My_Rectangle(object obj) {
        _obj = obj;
    }
}

Then I would simply create the object like this:

object obj = new object();
var myRectangle = new My_Rectangle(obj);

I personally didn't have much hope for either of these methods... So I am turning to this community hoping to achieve some sense of clarity on how I can do this.

If I was unclear or it seems I was unspecific, consider my inexperience and request that I clarify.

Best regards!

Edit: I found out about the Tag property, and this seems to do the trick.

var rectangle = new Windows.UI.Xaml.Shapes.Rectangle();
object obj = new object();
rectangle.Tag = obj;

If there is a way to perform my original question, that'd still be appreciated though :)

1

There are 1 answers

1
tmaj On

In many scenarios your 2nd option (class MyRectangle: Rectangle) would work.

However, Windows.UI.Xaml.Shapes.Rectangle is a sealed: public sealed class Rectangle : Shape. This means that other classes are forbidden from inheriting from it. Please see sealed (C# Reference) for more info.

You could reverse what you do and have a class that stores extra information and have the rectangle too.

class RectangleAndX
{
  public Windows.UI.Xaml.Shapes.Rectangle Rectangle { get; set; }
  public ClassX X { get; set;}
}

BTW. You generally need to avoid working with object type, especially at the beginning of your progamming journey.