user1920206
user1920206

Reputation: 69

Accessing an array from anywhere

I have a static array which uses a static variable called Variables.rows to define the number of rows in the array. Variables.rows is defined in another static class called Variables.

public static class TheArrayClass
{
    public static double[,] HiThere = new double[Variables.rows, 6];
}

My problem is that the static array is created as soon as the project in run (I believe). This means that the methods needed to assign the correct value to Variables.Rows are not executed in time. This means that I get an index error when populating the array because the array does not have the correct size.

I need a way around this so that I can access the array from anywhere in my code please.

Upvotes: 0

Views: 243

Answers (3)

Jonathan Wood
Jonathan Wood

Reputation: 67195

It's interesting that you didn't show where Variables.Rows was defined. Either way, you can perform whatever initialization you want in the classe's constructor.

public static class TheArrayClass
{
    public static double[,] HiThere;

    static TheArrayClass()
    {
         HiThere = new double[Variables.rows, 6];
    }
}

Upvotes: 1

Dustin Kingen
Dustin Kingen

Reputation: 21245

Try message passing between your forms.

public partial class Form1 : Form
{
    private string _data;

    public Form1()
    {
        InitializeComponent();
        _data = "Some data";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2();
        form2.Data = _data;
        form2.Show();
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public string Data { get; set; }
}

Upvotes: 2

lolol
lolol

Reputation: 4390

I think you have a design problem, so I'm gonna try to add some information that can help you to solve your problem.

First, a static class is, in fact, created as soon as the project runs. But a static class can also have a static constructor (where you can define the variables.rows) that will also runs one time as soon as the project runs.

Also, maybe you should use an ArrayList (http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx) or GenericList (http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx), by doing that you can easily avoid the array variable limitations (like changing its size).

Upvotes: 0

Related Questions