Are member variables, by default, Public or Private in C#?

When we define types without placing a “public” or a “private” keyword at the front of the statement, is the associated variable public or private. For example, in:

Camera viewCamera;

RaycastHit m_hit;

Is viewCamera and m_hit a private or is it some other third state?

Ok, since no one is answering, let me ask the question differently:

Does
RaycastHit mHit;
behave differently to
private RaycastHit mHit; ???

Hi,

The default access modifier in C# is private for a class member, internal for a class.

public class Example
{
    int aNumber;  // private member variable of type int

    private int anotherNumber; // also a private member variable of type int

    public string excitingNewType; // public member variable of type string (for variety)
}
class AnotherExample  // internal access modifier
{
    
}

In the code example you posted, there is also another clue, the variable has a “m_” prefix. This is a little bit old school perhaps, but was used to designate member variables, member variables are typically private and may be exposed with properties, or, only used within methods.

Personally, I find not specifying access modifiers, even though not always necessary, to be a little lazy and, as demonstrated here, can lead to confusion.

Hope this helps :slight_smile:


See also;

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms