In Visual C # I cannot make my public class public
I am trying to create a Visual C # program that has my generated class and when the application starts it creates an array of my class object and this array of my object can be used throughout the program. Thus, any function or control event can access an array of objects and their member variables. I created my class as "public", but for some reason I am getting these errors when building: "The name" MyArrayObjectNameHere "does not exist in the current context" When I try to access the member variables of objects inside an event of the upload file dialog, in which I am trying to load data from a file into member variables of an object array.
Is there a specific place that an array of objects must be declared and constructed so that it exists in every context? If so, can you tell me where it is?
I am currently declaring it in the main function before starting the form.
My class definition looks like this in its own .cs file and program namespace:
public class MyClass
{
public int MyInt1;
public int MyInt2;
}
I declare an array of such objects inside the main function before loading the form:
MyClass[] MyArrayObject;
MyArrayObject = new MyClass[50];
for (int i = 0; i < 50; i++)
{
MyArrayObject[i] = new MyClass();
}
Thanks in advance for your help.
source to share
Your problem is that you are defining it inside the main function, so it will only exist inside the main function. you need to define it inside a class, not inside a 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
source to share
Only static objects are available in all contexts. While your design is missing ... er, just missing at all how you could do this is to add a second static class that maintains an 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;
}
}
}
Make yourself a fav and grab CLR Via C # from Jeffrey Richter. Skip the first chapters of the couple and read the rest.
source to share