0

I have the following code running as it should (albeit not special), but I'm trying to make the number of columns defined to be variable. Ideally, this would be done right here in the class. Is something like this possible? I'm using 4.8

public partial class Form1 : Form
    {
        class NodeN
        {
            public string NameN { get; set; }

            public string Column1 { get; set; }
            public string Column2 { get; set; }

            public NodeN(string name,string Col1, string Col2)
            {
                this.NameN = name;
                this.Column1 = Col1;
                this.Column2 = Col2;
            }
        }

        public Form1()
        {
            InitializeComponent();

            //startup stuff
        }
    }

What I'd like to do:

  public partial class Form1 : Form
    {
        public class NodeN
        {
            public string NameN { get; set; }

for (int i = 0; i <= numberofcolumns; i++)
{
    
    //create i column definitions
}
    
            public NodeN(string name, ???? )
            {
                this.NameN = name;
                ????
            }
        }

        public int numberofcolumns

        public Form1()
        {
            InitializeComponent();

            numberofcolumns = 4
        }
    }
3
  • Yes, it's possible but there are many ways to achieve this. Your question is too broad at the moment and needs more details so that an appropriate answer can be given that fits your exact use case (which is still very much unclear). Commented Aug 13, 2023 at 22:35
  • 2
    Make the columns an array so you do not need to modify the source. Commented Aug 13, 2023 at 23:19
  • Excelent idea jdweng, I'm using a list right now (to keep the size variable) and it works indeed. Commented Aug 13, 2023 at 23:46

1 Answer 1

0

There are some ways to generate code at runtime, but this is complicated, and really not what you want to do here.

What you should do is inject some form of collection:

  • If you do not need to modify the columns after creation, use a IReadOnlyList<string>
  • If you need to modify the values, but not the number of columns, use an, array.
  • If you need to modify both the values and the number of columns, us a List<string>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.