[dba-VB] C#: Did you know - private fields and properties are available to instance methods of other instances of the same class?

Salakhetdinov Shamil mcp2004 at mail.ru
Sun Jun 24 02:28:43 CDT 2012

Hi All --

I was surprised this morning - the following code snippet will compile and work in C#:

public class TestMe
    private string m_someString;
    //this also works: private string b_someString { get; set; }
    public TestMe(string someString)
        m_someString = someString;

    public void RunTest(TestMe other)
        if (other.m_someString == this.m_someString)
            System.Console.WriteLine("this.'{0}' equals other.'{1}", 
                this.m_someString, other.m_someString);  
            System.Console.WriteLine("this.'{0}' NOT equals other.'{1}", 
                this.m_someString, other.m_someString);  


Compare it to VBA - the following code will not compile:

' class TestMe

Private m_someString As String

Public Sub Init(ByVal someString As String)
    m_someString = someString
End Sub

Public Sub RunTest(ByRef other As TestMe)
Dim message As String
    message = "this.'{0}' {1} other.'{2}'"
    If (other.m_someString = Me.m_someString) Then
        message = Replace(message, "{1}", "equals")
        message = Replace(message, "{1}", "not equals")
    End If
    message = Replace(message, "{0}", m_someString)
    message = Replace(message, "{2}", other.m_someString)
    Debug.Print message
End Sub

I have then consulted C# docs:


where I have read:

"Finally, a class or struct member can be declared as private with the private keyword, indicating that only the class or struct declaring the member is allowed access to that member."

I must note I have never thought the above sentence means that private members of a class or struct instance are allowed to be accessed by other instances of the same type of class or struct, have you?

Thank you.

-- Shamil

P.S. I have used m_ prefix in declaring C# private fields or properties only in this sample - I usually use

- undescore ('_') prefix for private fields and
- lowerCaseCamelCase for private properties, methods, ....

More information about the dba-VB mailing list