- Home /
How to access individual class elements, that has an array, that is in a list for c#
Hello,
I am still pretty new to programming.
So I have created a class named SetMatch. Within this class I have 2 arrays, 1 of type int, the other of type bool. I then have created a list of this class and named it setmatch. When I save the script, it saves fine with no errors so I know that c# has allowed this but I am having trouble finding how to access an individual element of 1 of the arrays.
I know that with a class .dot notation is used to access the fields and that with list types you are capable of accessing individual elements like you would with an array, ex. mylist[0]. bellow is my sample coding for a clearer picture of what I am trying to do.
class SetMatch
{
int[] piece = new int[7];
bool[] matched = new bool[7];
}
List<SetMatch> setmatch = new List<SetMatch>();
it is at this point that i would like to try and access an individual element of 1 of the arrays, something like this.
setmatch[0].piece[0] = 12; setmatch[0].matched[0] = false;
but the word piece automatically turns red in my user interface so I know it is not correct and when I'm close it gives me auto fill suggestions. I know there is other ways of doing what I am trying to achieve but sense I have created a class with arrays in it and made a list of the class and rules allowed it seems like there should be a way to access the individual elements. Please help, It's hard for me to move on until I have problems and curiosity's learned and solved be for moving on. If more information for under standing what I'm trying to do please let me know and thank you in advanced.
What it is error reported with the red underline/squiggle or whatever? Hovering over it should tell you. setmatch[0].piece[0] = 12; setmatch[0].matched[0] = false;
should work just fine. I'm guessing there is something else going on here.
Answer by Buckslice · Dec 02, 2017 at 05:04 AM
Your notation for accessing elements in the arrays and lists is correct. However you probably need piece and matched to be public variables to be able to access them. Also make sure the List is being declared inside of a class if it isn't.
class SetMatch
{
public int[] piece = new int[7];
public bool[] matched = new bool[7];
}
List<SetMatch> setmatch = new List<SetMatch>();