C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Scope and Access ModifiersThe 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#:
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 using System.Collections; using System.Collections.Generic; using UnityEngine; public class MyClass { public int apples; public int bananas; private int stapler; private int sellotape; public void FruitMachine(int a, int b) { int answer; answer = a + b; Debug.Log("Fruit total: " + answer); } private void OfficeSort(int a, int b) { int answer; answer = a + b; Debug.Log("Office Supplies total: " + answer); } } AccessModifiers.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AccessModifiers : MonoBehaviour { public int alpha = 5; private int beta = 0; private int gamma = 5; private MyClass myOtherClass; void Start() { alpha = 29; myOtherClass = new MyClass(); myOtherClass.FruitMachine(alpha, myOtherClass.apples); } void Example(int pens, int crayons) { int answer; answer = pens * crayons * alpha; Debug.Log(answer); } void Update() { Debug.Log("Alpha is set to: " + alpha); } } 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. Here, I changed the value of the Alpha variable to 67 at the run time, and then the output is:
Next TopicData Types
|