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.
Array2D.zeroCreate 5 5indeed creates 25 null instances ofCellclass. If you want to initialize them with a default value, you should use:otherwise you have to assign each element of the matrix to a
Cellinstance before accessing their methods and fields.Another problem is mutable values
xPositionandyPositionare initialized to0regarding 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: