11.5. Property Accessibility

Good coding practices state that fields should be private and wrapped with a property. This property should be used to access the backing field, rather than to refer to the field itself. However, one of the difficulties has been exposing a public read property so that other classes can read the value, but also making the write part of the property either private or at least protected, preventing other classes from making changes to the value of the field. The only workaround for this was to declare two properties, a public read-only property and a private, or protected, read-write, or just write-only, property. Visual Studio 2008 lets you define properties with different levels of accessibility for the read and write components. For example, the Name property has a public read method and a protected write method:

C#

public string Name
{
    get { return m_Name; }
    protected set { m_Name = value; }
}

VB.NET

Public Property Name() As String
    Get
        Return Me.m_Name
    End Get
    Protected Set(ByVal value As String)
        Me.m_Name = value
    End Set
End Property

The limitation on this is that the individual read or write components cannot have an accessibility that is more open than the property itself. For example, if you define the property to be protected, you cannot make the read component public. Instead, you need to make the property public and the write component protected.

Get Professional Visual Studio® 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.