I’m having some problems with encapsulation in C#. There are two specific scenarios that are causing me problems and I believe the issue is related.
Scenario #1
I have a class definition that looks something like this
class MyClass
{
private int _someField;
private OtherClass _otherClass;
public int someField
{
get { return _someField; }
set { _someField = value; }
}
public OtherClass otherClass
{
get { return _otherClass; }
set { _otherClass = value; }
}
}
If I then try and do something like this in a new piece of code
MyClass theClass = new MyClass();
theClass.otherClass.XYZ += 1;
I get told Cannot Modify the return value of ‘MyClass.otherClass’ because it is not a variable.
Scenario 2#
public partial class trksegType
{
private wptType[] trkptField;
private extensionsType extensionsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("trkpt")]
public wptType[] trkpt
{
get
{
return this.trkptField;
}
set
{
this.trkptField = value;
}
}
}
If I now try and foreach through the wptType array:
foreach (wptType way in trk.trkseg[i])
I get told – foreach statement cannot operate on variables of type ‘trksegType’ because ‘trksegType’ does not contain a public definition for ‘GetEnumerator’
Even though an array should implicitly allow enumeration.
Can anyone explain what’s going on and what I can do to get around this problem, whilst still maintaining best practices.
(You really shouldn’t post two questions in one.)
Scenario 1
This error happens because
OtherClassis not a class, but a struct — also called a value type. This means that accessingMyClass.otherClasscopies the value instead of returning a reference. You would be modifying this copy, which would be pointless. The compiler catches this because it is always a bug and never useful.Scenario 2
You haven’t told us what
trkseg[i]is, but if it is of the typetrksegType, then the answer is: becausetrksegTypedoesn’t allow any enumeration. It does not implementIEnumerable,IEnumerable<T>, nor does it have aGetEnumeratormethod of its own.Perhaps you meant to write:
because
trkptis an array ofwptType. (You might have found this error sooner if you used more meaningful variable names instead of weird combinations of letters that make no sense.)