Private Methods in C#

CsharpProgrammingServer Side Programming

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.

raja
Published on 14-Aug-2018 16:30:57
Advertisements