user3905287 user3905287 - 3 months ago 13
C# Question

Storing an array of structs in GlobalVariables.cs in C#

I have an array of structs. How do I store them globally in GlobalVariables.cs? When I try, it gives an error saying it is inaccessible due to its protection level. Please Help!

Here is the GlobalVariables.cs code:

public class GlobalVariables
{
List<Employee[]> persons = new List<Employee[]>();
}


Here is the form code:

List<Employee> persons = new List<Employee>()
{
new Employee { Name = "alfred", Id = 203476, Authority = "1" },
new Employee { Name = "barbara", Id = 182856, Authority = "4" },
new Employee { Name = "chris", Id = 398046, Authority = "2" },
};


And here is the Employee Struct:

public struct Employee
{
public string Name;
public int Id;
public string Authority;
}

Answer

I'm not sure from your code what you're trying to do, but if you make GlobalVariables a static class (public static class GlobalVariables) and then access it like GlobalVariables.persons from your other classes, things should be okay. If that doesn't work, try to explain a little more what you want to do with your code.

public static class GlobalVariables
{
   public static List<Employee[]> persons = new List<Employee[]>();

//fields of static classes need to be static and public if accessed from other classes }

Then (from another class):

Employee person = new Employee();
GlobalVariables.persons.Add(person);

EDIT: whoops - just noticed your global list is a list of arrays, so you would add person[] instead of person. Not sure why you want to do that, but the code above answers your question of global access through the use of public static.

on a side note, the use of

List<Employee>

would be much easier than

List<Employee[]> 

for most purposes. you can always group your list if needed using something like

GlobalVariables.persons.Where(p=>p.Authority=="2");

if you really NEED to group your employees, it might be better to use a global Dictionary<> rather than a list of arrays.