Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct - access to private fields

Tags:

c#

struct

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.  
    }
}
like image 714
apocalypse Avatar asked Nov 28 '22 17:11

apocalypse


2 Answers

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.

like image 96
Benjamin Cutler Avatar answered Dec 05 '22 16:12

Benjamin Cutler


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 is private, the accessibility domain of M is the program text of T.

like image 45
Jon Skeet Avatar answered Dec 05 '22 16:12

Jon Skeet