Javatpoint Logo
Javatpoint Logo

Scope and Access Modifiers

The scope of a variable is the area in code that can be used by the variables. A variable is supposed to be local to the place in code that it can be used. Code blocks are generally what defines a variable's scope, and are denoted by the braces.

Access modifiers are the keywords. These modifiers are used to specify the declared accessibility of a member or a type. There are four access modifiers in C#:

  • public
  • protected
  • internal
  • private

The following six accessibility levels can be specified in C# using the access modifiers are given below:

public: In this, access is not restricted.

protected: Here, access is limited to the class in which it is contained.

internal: In this case, access is limited to the current assembly.

protected internal: For this access is limited to the current assembly.

private: Access is limited to the containing type.

private protected: For this access is limited to the containing class or types derived from the containing class within the current assembly.

Example:

In this example, everything within the class can be said to be local to that class. The variables crayons, pens, and answers are all local to the example function and can?t be used outside. You would say that the variables beta, alpha, and gamma are in scope within the scope and access modifiers class. And you would say that the crayons, pens, and answer variables are in scope within the example function.

MyClass.cs

AccessModifiers.cs

Output:

When you run the game, then you can see that public variable alpha is included as a property that you can edit. This allows the users to edit the variables while they run the game. Imagine, for example, the value controls the speed of a car, and it would be nice to be able to tweak that variable while testing it without having to stop. As such, it makes sense o have this be a public variable.

Scope and Access Modifiers
Scope and Access Modifiers
Scope and Access Modifiers

Here, I changed the value of the Alpha variable to 67 at the run time, and then the output is:

Scope and Access Modifiers
Next TopicData Types




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA