Private Access Modifier in C#

In this article I will explain private access modifier in C#.
  • 3038

Introduction

Private access is the least permissive access level. It allows a class to hide its member variables and member functions from other functions and objects. Functions of the same class can access its private members. It is quite clear, if you declare any variables or methods in C# as private, then they can only be used inside the class. You cannot call the private method using the class object.

Accessibility


Cannot be accessed by object.

Cannot be accessed by derived classes.

 

Example

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Private_Access_Specifiers

{

    class accessmod

    {

        // String Variable declared as private

        private string name;

        // Public method

        public void print()

        {

            Console.WriteLine("\nMy name is " + name);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            accessmod nam = new accessmod();

            Console.Write("Enter your name: ");

            // Accepting value in public variable that is outside the class

            nam.name = Console.ReadLine();

            nam.print();

         Console.ReadLine();

        }

    }

 

The above program will give compilation error, as access to private is not permissible. In the below figure you can see the private member nam.name is not accessible due to its protection level.

 

 Clipboard120.jpg

© 2020 DotNetHeaven. All rights reserved.