tags:

views:

574

answers:

4

I'm trying to make a program in Visual C# that has my one created class, and at application launch it creates an array of my class object, and this array of my object can be used all over the program. So any function, or a control's event can access the array of objects and their member variables. I created my class as "public" but for some reason i get these errors upon build: "The name 'MyArrayObjectNameHere' does not exist in the current context" When I try to access the objects member variables inside a load file dialog event in which I am trying to load data from a file into the member variables of the object array.

Is there a certain place the object array needs to be declared and constructed so it exists in every context? If so, can you tell me where this is?

I currently declare it in the main function before form1 is run.

My class definition looks like this in its own .cs file and the programs namespace:

public class MyClass
{
    public int MyInt1;
    public int MyInt2;
}

I declare the array of objects like this inside the main function before the form load:

MyClass[] MyArrayObject;
MyArrayObject = new MyClass[50];
for (int i = 0; i < 50; i++)
{
    MyArrayObject[i] = new MyClass();
}

Thanks in advance for any help.

A: 

Only static objects are available in all contexts. While your design lacks... er, just lacks in general, the way you could do this is to add a second, static class that maintains the array of your MyClass:

public static class MyClassManager
{
  private MyClass[] _myclasses;
  public MyClass[] MyClassArray
  {
    get
    {
      if(_myclasses == null)
      {
      _myClasses = new MyClass[50];
      for(int i = 0; i < 50;i++)
        _myClasses[i] = new MyClass();
      }
      return _myclasses;

    }
  }
}

Do yourself a fav and grab CLR Via C# by Jeffrey Richter. Skip the first couple chapters and read the rest.

Will
A: 

You need to make the array a static member of some class, .NET does not have a global scope outside of any class.

e.g.

class A
{
    public static B[] MyArray;
};

You can then access it anywhere as A.MyArray

Rob Walker
+4  A: 

Your problem is that you are defining it within the main function, hence it will only exist inside the main function. you need to define it inside the class, not inside the function

public partial class Form1:Form
{
MyClass[] MyArrayObject; // declare it here and it will be available everywhere

public Form1()
{
 //instantiate it here
 MyArrayObject = new MyClass[50];
 for (int i = 0; i 
Kevin
It works, thank you very much sir.
timmyg
A: 

That't good.It is very useful for learners like me.