C# Public

  • The public keyword is one of the access modifiers in C#.
  • The public modifier means you can access the types or type members from anywhere in any assemblies.
  • The public keyword gets the most broad access level with the least security level because the public items can be accessed by any codes.
  • public is always used in methods to give the outside code interfaces to access the private fields of the class.

public class can be created as follows.

public class MyClass
{
......
}

This means the class can be accessed from anywhere if the assembly of the class is referenced.

Example 01-46-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace TestPublic
{
    public class MyClass
    {
        public int a = 10;
        public string b = "test";

        public void testPublic()
        {
            Console.WriteLine("Output from testPublic method.");
        }
    }
    
    class TestMyClass
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            Console.WriteLine("a = {0}, b = {1}", mc.a, mc.b);
            mc.testPublic();
            Console.Read();
        }

    }
}

Output

a = 10, b = test
Output from testPublic method.
  • Line 5-14: Define a public class named with MyClass.
  • Line 7-8: Declare 2 public fields of the class.
  • Line 10-13: Define a method testPublic() with void return type.
  • Line 12: In the method, output a string.
  • Line 16-26: Define a class TestMyClass.
  • Line 18: Main method starts. This is the entry point of running the program.
  • Line 20: Instantiate MyClass.
  • Line 21: Output the default values of the 2 fields defined in line 7-8.
  • Line 22: Call the method testPublic() to output the string.