xarzu xarzu - 7 days ago 5
C# Question

Why can't you access parts of a class in C# like you could a struct in C++?

namespace SnakesAndLadders
{

class Node
{
int snakeHead ; // points to another node where the player goes down to
int ladderFoot; // points to another node where to player goes up to
}

class Program
{
Node[] gameBoard = new Node[100];

void loadStructure()
{
// first, set all the snakeheads and ladderFoots to zero
for (int i =0; i < 100; i++)
{
gameBoard[i].snakeHead = 0;
gameBoard[i].ladderFoot = 0;
}
}
static void Main(string[] args)
{
}
}


In C#, this won't work. For gameBoard[i], intellisense does not show it has a component of snakehead.

Answer

In C# fields of a class are private by default

class Node
{
    public int snakeHead ;   // points to another node where the player goes down to 
    public int ladderFoot;  // points to another node where to player goes up to
}

Just making your fields public should fix your issue. EDIT: using best practices you would keep fields private, but create properties and use them to deal with your data. Also naming private with an underscore is a common practice:

class Node
{
    private int _snakeHead ;   // points to another node where the player goes down to 
    public int SnakeHead
    {
        get {return _snakeHead;}
        set {_snakeHead = value;}
    }

    private int _ladderFoot;  // points to another node where to player goes up to
    public int LadderFoot
    {
        get {return _ladderFoot;}
        set {_ladderFoot = value;}
    }
}