'Create custom properties at runtime

I am trying to create a custom property (like Name, BackgroundImage etc.) for my dynamically created PictureBox called "angle". And use it like that: PictureBox.angle = 20; Is there a way to do that? Any help is appreciated.



Solution 1:[1]

Create a custom component (Right click Project -> Add -> Component). Change it to inherit from PictureBox, and add the property.

using System.ComponentModel;

namespace Playground.WinForms
{
    public partial class MyCustomPictureBox : PictureBox
    {
        public int Angle { get; set; }

        public MyCustomPictureBox()
        {
            InitializeComponent();
        }

        public MyCustomPictureBox(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }
    }
}

When you build your WinForms solution, it will appear in your Toolbox, at which point your can drag it onto your form, or create one dynamically as you mentioned above.

enter image description here

Solution 2:[2]

var v = new { Amount = 108, Message = "Hello" };

// Rest the mouse pointer over v.Amount and v.Message in the following // statement to verify that their inferred types are int and string. 
Console.WriteLine(v.Amount + v.Message);

Try use anonynous types

https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/anonymous-types

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew M.
Solution 2 DamnScandalous