Click here to download the sample source code for this Public versus Private Methods lab exercise
Classes can contain both public and private Methods. Methods that are declared as public can be called from outside the class and inside the class (by other Methods in the class). In the previous exercise Calling User defined Classes, the Method AddTwoNumbers is a public Method. That is why I was able to call it from my ASP.NET web page Default.aspx.
Methods that are declared as private CANNOT be called from outside the class, so by design they are hidden to the external program. Private Methods can only be called from inside the class by other Methods in the class. Let’s look at an example of a private Method. Add the following Method to the Arithmetic Class from the previous example:
private int MultiplyTwoNumbers(int iNum1, int iNum2) { return iNum1 * iNum2; }
Now go back to the code for the Button click (Button1_Click) in Default.aspx.cs and try to call the Method MultipleTwoNumbers:
int iMultiplyResult = mynewclass.MultiplyTwoNumbers(50, 20);
If you right click on the project name in the Solution Explorer and choose Build Web Site you will get a compiler error: “Arithmetic does not contain a definition for MultiplyTwoNumbers”. This is because that Method is Private, thus it cannot be accessed from outside the Class Arithmetic.
Usually private Methods are used in situations where you have a lot of redundant code throughout different Methods in a Class and you want those Methods to share some common code.