Why does it not generate an error?
If i try change private field of this struct in main program file - it generates an error, but not in struct implementation.
public struct MyStruct
{
private int privateField;
public int MyField
{
get { return privateField; }
set { if (value >= 0) privateField = value; else value = 0 }
}
public void SomeMethod (MyStyruct s)
{
s.privateField = 10; // no error here.
}
}
Private members are restricted to the class or struct not the object. In this case, even though s
is a different object from this
, it still works.
Firstly, this has nothing to do with whether it's a struct or a class - or indeed whether it's a field or some other member.
Accessibility in C# is decided based on where the code is, not whether it's "this object" or another object.
Section section 3.5 of the C# specification for more details. For example, from 3.5.2:
The accessibility domain of a member consists of the (possibly disjoint) sections of program text in which access to the member is permitted.
[...]
If the declared accessibility of
M
isprivate
, the accessibility domain ofM
is the program text ofT
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With