What is 'public' keyword good for in C#?

Experience Level: Junior
Tags: C#

Answer

The 'public' keyword is an access modifier. It makes a method visible to the code that lives outside of the class that holds the method that is marked by the 'public' keyword.

In the example below there are two classes. The class Progam contains a method Main. When this method gets called, it creates a  new radio object and stores it to myRadio variable. Then it calls the method TurnOn on the object that is stored in the myRadio variable which will then turn the radio on.

The method TurnOn() is defined in the Radio class and it can be called from within the class Program because it is marked as public by the access modifier 'public'.

Now have a look at the method TurnOff(). This method doesn't have the access modifier 'public' so it won't be possible to call it from the method Main of the class Program.
 

Example
public class Program
{
  public static void Main()
  {
    var myRadio = new Radio();
	myRadio.TurnOn();
  }
}

public class Radio
{
  public void TrunOn()
  {
    // Some code here
  }
  
  void TurnOff()
  {
    // Some code here
  }  
}

Comments

No Comments Yet.
Be the first to tell us what you think.
C# for beginners
C# for beginners

Are you learning C# ? Try our test we designed to help you progress faster.

Test yourself