Property question

  • Thread starter Thread starter Aamir Mahmood
  • Start date Start date
A

Aamir Mahmood

Hi All,

Is it possible to make a property in C# in which 'set' is private (or
protected or internal) but 'get' is public?

-
Aamir
 
Yes, do not implement the set method, and then add an internal property with
the set implemented. The language itself does not have special features for
what you want, sometimes you just have to be creative.

JIM
 
Aamir Mahmood said:
Hi All,

Is it possible to make a property in C# in which 'set' is private (or
protected or internal) but 'get' is public?

-
Aamir
I may be missing the point, but what purpose would a private set method
serve? Private members are directly accessible to code within a class, so no
set method is needed from within.
I think all you'd need is a get method, effectively making the property
"read only" as seen from outside the class.
 
Using a private set lets you validate (or trace, log, persist) easily
(assuming you always use set instead of assigning to the private
variable directly).
 
Sometimes a property is helpful, if only as syntactic sugar, within the
class too. Just because you can access the internal state directly doesn't
mean that it's always the nicest way. For instance:

class JaggedArray<T> {
T[][] manyTs;
foo(int[] cols, int rows) {
manyTs = new T[rows];
int colsIndex = 0;
foreach (T[] S in manyTs) {
S = new T[cols[colsIndex++]];
}
}
public T this[int col, int row] {
get {
if(row < manyTs.Count &&
col < manyTs[row].Count) {
return manyTs[row][col];
} else {
throw System.IndexOutOfRangeException;
}
}
set {
if(row < manyTs.Count &&
col < manyTs[row].Count) {
manyTs[row][col] = value;
} else {
throw System.IndexOutOfRangeException;
}
}
}
}

Note that the get and set accessors are somewhat complex. Even within the
class, say in an iterator or something, you might well like to be able to
use the 'this[col,row]' notation to access an individual element in the
jagged array rather than repeating the index-checking logic every time you
needed to access an element. If, for some reason, you needed your
JaggedArray class to be read only then, as the original poster indicated,
you might well want different protection levels for 'get' and 'set'.
 
Peter van der Goes said:
I may be missing the point, but what purpose would a private set method
serve? Private members are directly accessible to code within a class, so
no set method is needed from within.
I think all you'd need is a get method, effectively making the property
"read only" as seen from outside the class.
Thanks, Fred and Jason, for opening my eyes to possibilities I'd not
considered.
These groups are a great learning place :)
 
Back
Top