Public and Private Access Modifier in C#

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.

  1. using System;  
  2. class A   
  3. {  
  4.     public int x, y, z;  
  5. }  
  6. class Demo   
  7. {  
  8.     public static void Main()   
  9.     {  
  10.         A obj;  
  11.         obj = new A();  
  12.         obj.x = 10;  
  13.         obj.y = 20;  
  14.         obj.z = obj.x + obj.y;  
  15.         Console.WriteLine(obj.z);  
  16.     }  
  17. }  
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.
  1. using System;  
  2. class A   
  3. {  
  4.     private int x, y, z;  
  5.     public void AcceptData()   
  6.     {  
  7.         Console.WriteLine("enter 2 numbers");  
  8.         x = Int32.Parse(Console.ReadLine());  
  9.         y = Int32.Parse(Console.ReadLine());  
  10.     }  
  11.     public void Add()   
  12.     {  
  13.         z = x + y;  
  14.         Console.WriteLine("sum is:" + z);  
  15.     }  
  16. }  
  17. class Demo   
  18. {  
  19.     static void Main()   
  20.     {  
  21.         A obj = new A();  
  22.         obj.AcceptData();  
  23.         obj.Add();  
  24.     }  
  25. }  

Ebook Download
View all
Learn
View all