[dba-VB] C#: Did you know - private fields ...

Gustav Brock gustav at cactus.dk
Sun Jun 24 04:09:02 CDT 2012


Hi Shamil

No I didn't. On the other hand, I've never attempted to do so. As you and most others, I use naming conventions to separate local variables and fields from public.

/gustav


>>> Salakhetdinov Shamil <mcp2004 at mail.ru> 24-06-12 9:28 >>>
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);  
        else
            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")
    Else
        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:

http://msdn.microsoft.com/en-us/library/ms173121(v=vs.80).aspx

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