TaylorE
TaylorE

Reputation: 181

Access modifiers in C#

I am teaching myself C# and I have run into a bit of an ambiguous situation.

What I'm trying to do is create a container class for some data, fairly straight forward but I am trying to respect encapsulation and have the data accessible via setters and getters only. So I am reading about access modifiers and according to This MSDN article the default access level is Internal. I am from Java-land so I am not familiar with internal, however from the resources on that page, it looks like Internal is more permissive than I want to be. So I want to set things as private.

My confusion arises from the code example here. it looks like if I do

class whatever {
    private int thing;
    string ambiguous; 
}

the ambiguous variable will be private, not internal.

Does it actually work like that? Or is the second example mis-written?

Upvotes: 3

Views: 150

Answers (1)

Dai
Dai

Reputation: 155025

The field ambiguous is not ambiguous at all. The C# specification states that in the absence of an access modifier on a class member it defaults to private.

The default access level on top-level types is internal.

class Foo {
    int bar;
    class Nested {
        int baz;
    }
}

is equivalent to

internal class Foo {
    private int bar;
    private class Nested {
        private int baz;
    }
}

Upvotes: 8

Related Questions