Access modifiers allow you to define who does or doesn't have access to certain features.
A Class Consists Members (i.e. Variables, Functions, Constructors, Destructors, Properties and Events.)
Public
Public members can be access from outside the class after creating an object.
- using System;
- class A
- {
- public int x, y, z;
- }
- class Demo
- {
- public static void Main()
- {
- A obj;
- obj = new A();
- obj.x = 10;
- obj.y = 20;
- obj.z = obj.x + obj.y;
- Console.WriteLine(obj.z);
- }
- }
Private
private members cannot be accessed from outside the class but they can be accessed only with in the class by other members of the class.
By default the members are declared as private.
- using System;
- class A
- {
- private int x, y, z;
- public void AcceptData()
- {
- Console.WriteLine("enter 2 numbers");
- x = Int32.Parse(Console.ReadLine());
- y = Int32.Parse(Console.ReadLine());
- }
- public void Add()
- {
- z = x + y;
- Console.WriteLine("sum is:" + z);
- }
- }
- class Demo
- {
- static void Main()
- {
- A obj = new A();
- obj.AcceptData();
- obj.Add();
- }
- }