Reputation: 3943
I have this class
class cell
{
public cell()
{
T= -1;
M= -1;
s= false;
}
public cell(int T, int M)
{
this.T= T;
this.M= M;
this.s= false;
}
int T;
int M;
bool s;
}
And this "matrix":
cell[,] test = new cell[10, 4];
I need then to access the field of my class cell and I tried this:
for (var i = startR; i < nR; i++)
{
for (var j = startR; j < nC; j++)
{
var p = test[i, j];
}
}
But if I try p.s
or p.T
or p.M
I can't see these attributes. Why? How can I access these fields?
Upvotes: 0
Views: 80
Reputation: 12201
Your fields are private
(private
is default access modifier inside class). Make all fields public
:
public int T;
public int M;
public bool s;
Or better way
You can change fields to public
auto properties (because fields should not be public
):
public int T { get; set;}
public int M { get; set;}
public bool s { get; set;}
Or
If you want fields and properties:
int T;
int M;
bool s;
public int TProperty
{
get {return T;}
set {T = value;}
}
public int MProperty
{
get {return M;}
set {M = value;}
}
public bool SProperty
{
get {return s;}
set {s = value;}
}
Then to read or write simply use these properties:
var p = test[i, j];
var m = p.MProperty;
p.TProperty = 5;
Upvotes: 2
Reputation: 764
You can create public readonly auto properties, eg. like in the following example:
class cell
{
public cell()
{
T = -1;
M = -1;
S = false;
}
public cell(int t, int m)
{
T = t;
M = m;
S = false;
}
public int T { get; }
public int M { get; }
public bool S { get; }
}
Setting values from the constructor (as you've already done) and using readonly properties is usually a better option than exposing public setters (unless you have a good reason to do so), as your instances of the cell
class will be immutable and won't be changed after the instantiation.
Upvotes: 0