Yabert Yanuar
Yabert Yanuar

Reputation: 1027

How to create an 2D Array but the content is a class?

Sorry, I don't know how express my question,
i have some code in C# :

public class Cell
{
    public bool boo;
    public bool boo2;

    public int xPos;
    public int yPos;

    public Cell(int xPosition, int yPosition)
    {
        xPos = xPosition;
        yPos = yPosition;
    }

    public void SomeMethod()
    {
        boo = false;
        boo2 = true;
    }

    public void SomeMethod2()
    {
        boo = true;
        boo2 = false;
    }
}

and i create a instance like this :

public static Cell[,] w;
public Cell c

w = new Cell[5,5]
...
//some other code

and the result from the code above is i can access method and properties from Cell Class, I try to make the same code in F#

type Cell(xPosition:int,yPosition:int) = 

    let mutable m_boo = false
    let mutable m_boo2 = false

    //x and y position of cell in picture box
    let mutable xPosition = 0
    let mutable yPosition = 0


    new(xPosition,yPosition) = new Cell(xPosition,yPosition)
    new() = new Cell(0,0)

    member this.xPos with get() = xPosition
                     and set newX = xPosition <- newX
    member this.yPos with get() = yPosition
                     and set newY = yPosition <- newY
    member this.boo with get() = m_boo
                         and set newBoo = m_boo <- newBoo
    member this.boo2 with get() = m_boo2
                         and set newBoo2 = m_boo2 <- newBoo2
    member this.SomeMethod() = 
        this.boo <- false
        this.boo2 <- true
    member this.SomeMethod2() = 
        this.boo <- true
        this.boo2 <- false

and i try to create the instance :

let worldGrid:Cell[,] = Array2D.zeroCreate 5 5
worldGrid.[0,0].SomeMethod2()

The result when the code compiled is :

System.NullReferenceException: Object reference not set to an instance of an object

is something not right in my code or am i doing it wrong? Hopefully with read the code help to understand my question.

Upvotes: 1

Views: 187

Answers (1)

pad
pad

Reputation: 41290

Array2D.zeroCreate 5 5 indeed creates 25 null instances of Cell class. If you want to initialize them with a default value, you should use:

let worldGrid = Array2D.init 5 5 (fun _ _ -> Cell())

otherwise you have to assign each element of the matrix to a Cell instance before accessing their methods and fields.

Another problem is mutable values xPosition and yPosition are initialized to 0 regarding parameters of the constructors. Furthermore, these mutable values and the class's parameters should have different names to avoid shadowing and confusion. The class could look like this:

type Cell(xPos:int, yPos:int) = 

    let mutable m_boo = false
    let mutable m_boo2 = false

    // x and y position of cell in picture box
    let mutable xPosition = xPos
    let mutable yPosition = yPos

    // ...

Upvotes: 2

Related Questions