Private Methods in C#


Private Methods can only be used inside the class. To set private methods, use the private access specifier.

Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.

The following is an example −

Example

using System;

class Demo {
   private int displayOne() {
      return 10;
   }

   public int displayTwo() {
      return 10;
   }
}

class Program {
   static void Main() {
      Demo d = new Demo();

      // Console.WriteLine(d.displayOne());
      Console.WriteLine(d.displayTwo());
   }
}

In the above example, we cannot call the private method displayOne(). If we try to call, then an error would be visible.

Updated on: 21-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements