a C# learning space
|
Buy me a cup of coffee?
|
Objects
If you are unfamiliar with objects in programming, think of an object as something that has properties and methods. Properties can be things like color
and size. Methods do things that make the object work. Probably a little over simplified. So, let's take a look at a couple objects in the Sudoku Sharp
program.
The Grid Object
The Sudoku grid is a 9X9 grid that is made up of rows, columns, and boxes or 3X3 mini-grids. We define the grid object as a class.
namespace Sudoku_Sharp
{
class Grid : Object
{
private int cellWidth;
public int CellWidth
{
get { return cellWidth; }
set { cellWidth = value; }
}
}
}
Let's break this code down a bit. First of all we are saying that this grid object belongs to the Namespace Sudoku_Sharp, which simply means the grid object
is part of the Sudoku Sharp program. Next we are defining the Grid class as an object. And we are giving it a property called CellWidth. Within the class
itself (private) there is a variable called cellWidth and a variable that is for use outside of the class called CellWidth. Remember C# is case sensitive, so
it sees these as two different variables. The property of CellWidth is set and returned using the cellWidth within the class.
This might sound a bit confusing, but it allows us to use the
grid.CellWidth
inside our program to be able to change or set the width of a cell
within the grid.
Now let's take a look at what a method would look like. I wanted a way to easily grab the cell number from a row (col & box) in order to step through and
compare cells. Below is a snippet of the method that takes a row number as an arugument and returns an array of cell numbers within a row. This is using
the Switch conditional statement. So, for each RowNumber (1 through 9) a different set of cells gets returned. So, yes, there are 8 other Case statements.
public int[] GetCellsInRow(int RowNumber)
{
int[] RowCells = new int[9];
switch (RowNumber)
{
case 1:
int[] Row1Cells = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
RowCells = Row1Cells;
break;
}
}
A grid contains cells. Our next object.
The Cell Object
The Celll object is pretty simple. It is just made up of several properties. A cell has a background color. A cell has a cell value (0 through 9). A
cell can contain a given clue or a cell that needs to be solved. These are all examples of properties. That means an object doesn't have to have methods.