Introduction:

  • In this article we will explain how to use Private Access modifier in c# or What is Private Access modifier or why use Private  Access modifier in c# with example.
  • Description:

 

Private Access modifiers or specifiers is a keywords in c#. It restricts the use of methods and variables only within the class itself. It can’t be used from outside of the class.  


  • Example of C# Private Access Specifier


Let's take an example to demonstrate C# Private Access Specifier

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace AccessSpecifiers
{
    class PrivateUser
    {
       private string Username = "Aditya Kumar";
        private string designation = "Software Developer";
        private void GetUser()
        {
            Console.WriteLine("Name :" + Username);
        }
    } 
    class Program
    {
        static void Main(string[] args)
        {
            PrivateUser privateUser = new PrivateUser ();
         
           //Accessing private method 
            privateUser.GetUser(); //Compile Time Error
 
            //Accessing private variable 
            Console.WriteLine("Designation:" + privateUser.designation);//Compile Time Error
 
            Console.ReadLine();
        }
    }
}

 

Output:

private access specifier in c sharp


In this example, we have created two classes PrivateUser and Program. PrivateUser class contains

private data member and private method. We are accessing these private members from outside the class,

so there is compile time error.

 

I hope this article will help to you.

 


0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like