Private Access Specifier in C# Language

Introduction

As the name suggested private access specified allow a class to hide its member variable and member functions from other function and objects. It can be function of the same class access private members and instance of a class cannot access its private members.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace pivate_access_specifier

{

    class rectangle

    {

       

        private double length;     /*Private member variable define Length and width , which cannot be access in

                                    main() function. The member function Getdetails() , Returnarea() and Display()

                                    can access this variables*/

        private double width;

 

        public void Getdetails()

        {

            Console.WriteLine("Enter lengte of Rectangle=");

                length =Convert.ToDouble(Console.ReadLine());

                Console.WriteLine("Enter Width of Rectangle=");

                 width=Convert.ToDouble(Console.ReadLine());

        }

 

        public double ReturnArea()

        {

            return length * width;

        }

        public void Display()

        {

            Console.WriteLine("Length={0}", length);

            Console.WriteLine("Width={0}", width);

            Console.WriteLine("Area={0}", ReturnArea());

        }

    }

    class ExecuteArea

    {

        static void Main(string[] args)

        {

            rectangle rect = new rectangle();

            rect.Getdetails();                   /*The member function Getdetails and Display() is also declare Public, so can also be accessed

                                                      from main() using in instance of the Rectangle class, named rect */

           rect.Display();

 

        }

    }

}


Output


output.jpg

Ebook Download
View all
Learn
View all