r.r
r.r

Reputation: 7153

Default access modifier in C#

If I will create a new object like the following, which access modifier will it have by default?

Object objectA = new Object();

Upvotes: 13

Views: 8723

Answers (8)

Saroj Manik
Saroj Manik

Reputation: 1

The access specifier of class is internal.

The access specifier of a variable is private.

Upvotes: 0

fedotoves
fedotoves

Reputation: 767

It is private by default.

َََََ

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502536

Any member will always have the most restrictive one available - so in this case the accessibility of objectA is private. (Assuming it's an instance variable. It makes no sense as a local variable, as they don't have any access rules as such.)

So this:

class Foo
{
    Object objectA = new Object();
}

is equivalent to this:

internal class Foo
{
    private Object objectA = new Object();
}

The "default to most private" means that for types, the accessibility depends on the context. This:

class Outer
{
    class Nested
    {
    }
}

is equivalent to this:

internal class Outer
{
    private class Nested
    {
    }
}

... because you can't have a private non-nested class.

There's only one place where adding an explicit access modifier can make something more private than it is without, and that's in property declarations:

public string Name { get; set; } // Both public

public string Name { get; private set; } // public get, private set

Upvotes: 34

Oren A
Oren A

Reputation: 5900

For class members and struct members, including nested classes and structs, private is the default.

For classes and structs - internal is the default

You can check out MSDN for further reading..

Upvotes: 2

rudigrobler
rudigrobler

Reputation: 17143

Classes and structs are declared as internal by default!

Read more here

Upvotes: 0

Liggi
Liggi

Reputation: 744

The class/type itself will default to "internal". The object you create will default to "private".

Upvotes: 0

abatishchev
abatishchev

Reputation: 100308

void Foo()
{
    // private in method scope
    Object objectA = new Object();
}

class Bar()
{
    // private in class scrope
    Object objectA = new Object();
}

Upvotes: 3

Dan Tao
Dan Tao

Reputation: 128377

As a class member: private.

If it's a local variable declared within the body of a method, it has no accessibility outside that method. But I'm guessing you already knew that.

Upvotes: 2

Related Questions