Introduction:

In this article we will explain how to use Public Access modifier in c# or What is Public Access modifier or why use Public Access modifier in c# with example.

  • Description:

 

In c# Public Access modifiers and specifiers is a keywords  to specify the accessibility of a type and its members. The public access class member, that is defined as public can be accessed from outside of the class .A public member can be accessed from anywhere even outside the namespace that references it.

  • Example of C# Public Access Specifier

Let's take an example to demonstrate C# Public Access Specifier

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace AccessSpecifiers

{

    class PublicUser

    {

        public string designation = "Software Developer";

        string Username = "Aditya Kumar";

        public void GetUser()

        {

            Console.WriteLine("Name :" + Username);

        }

    } 

    class Program

    {

        static void Main(string[] args)

        {

            PublicUser publicUser = new PublicUser();

         

           // Accessing public function 

            publicUser.GetUser();

 

            // Accessing public variable 

            Console.WriteLine("Designation :" + publicUser.designation);

 

            Console.ReadLine();

        }

    }

}

 

Output:



In above example we have two data members and one function .that have designation” public variable

and GetUser() public function  and second “Username” which is not public variable. If we want to access designation” variable and GetUser() function outside of class we can access it  but if we want to

access Username” variable outside of class it will get error.

 

I hope this article will help to you.

 

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.