Public Access Modifier in C#

In this article I will explain public access modifier in C#.
  • 2223

Introduction

Public is the most common access specifier in C#. The public keyword is an access modifier for types and type members. It is quite clear, the "public" access modifier achieves the highest level of accessibility. If you define your class properties and methods as "public", then it can be used anywhere in your C# program.

Accessibility

 

Can be accessed by objects of the class.

Can be accessed by derived classes.

 

Example

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Public_Access_Specifiers

{

    class accessmod

    {

        // String Variable declared as public

        public string name;

        // Public method

        public void print()

        {

            Console.WriteLine("\nMy name is " + name);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            accessmod nam = new accessmod();

            Console.Write("Enter your name: ");

            // Accepting value in public variable that is outside the class

            nam.name = Console.ReadLine();

            nam.print();

         Console.ReadLine();

        }

    }


In the following example, the variable and method of accessmod is set to be "public", and outside the class, an instance is created of accessmod. Then the "print()" method and variable is accessed by nam .

 

The output of following program

 

 Clipboard118.jpg

© 2019 DotNetHeaven. All rights reserved.