Christian Hinge
Christian Hinge

Reputation: 23

How can I access a class array from another class

public partial class FormRestaurant : Form
     public Tables[] AllTables = new Tables[4];

I create an array of type Tables which is a class that I made. If I try to reference this from a third class (Parties.cs) by doing:

public void AssignTable()
    {
        for (int i = 0; i < **FormRestaurant.AllTables**.Length; i++)
        {
            if (**FormRestaurant.AllTables[i]**.TableCapacity <= PartySize)
            {

            }
        }
    }

I am told that I need an object reference. How exactly do I do this?

I tried making the array static but it didn't seem to work. Also I get this error when I try to make the AllTables array public.

Error 1 Inconsistent accessibility: field type 'Restaurant_Spil.Tables[]' is less accessible than field 'Restaurant_Spil.FormRestaurant.AllTables'

Upvotes: 0

Views: 9603

Answers (2)

DrewJordan
DrewJordan

Reputation: 5314

When it says you need an object reference, it's trying to tell you that it needs an instance of your class. Say you have your class:

public partial class FormRestaurant : Form
{
     public Tables[] AllTables = new Tables[4];
}

If you want to get the length of the Tables[] array in Parties.cs, then Parties needs an instance of FormRestaurant; it makes no sense to ask for the length of FormRestaurant.AllTables. Instead you should:

public class Parties
{
    int length;
    FormRestaurant f;
    public Parties()
    {
        f = new FormRestaurant();
        length = f.AllTables.Length;
    }
}

the f variable is the object reference that was mentioned in your first error.

Upvotes: 3

pascx64
pascx64

Reputation: 984

All you need to do is put your Tables class public. You cannot expose private field type in a public class

Upvotes: -1

Related Questions