Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 919
r.r Avatar asked Sep 09 '10 10:09

r.r


People also ask

What is the default access modifier?

The default access modifier is also called package-private, which means that all members are visible within the same package but aren't accessible from other packages: package com.

Are there access modifiers in C?

Master C and Embedded C Programming- Learn as you go Access Modifiers are used to implement data hiding in object oriented programming. There are three types of access modifiers used in C++. These are public, private and protected.

What is the default access specifier of class in C#?

The default access for a class member in C# is private. Member variables i.e. class members are the attributes of an object (from design perspective) and they are kept private to implement encapsulation.

What is the default access modifier of a class in C++?

Note: If we do not specify any access modifiers for the members inside the class, then by default the access modifier for the members will be Private.


1 Answers

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
like image 110
Jon Skeet Avatar answered Oct 01 '22 02:10

Jon Skeet