Private Access Modifier in C# with Example

C#Private access modifier in C# is only used when you want to use some type member within the containing type only and want to restrict it from accessing outside of the containing type.  All type members are by default Private, so it is not necessary to use Private keyword in front of them.  But it’s a good habit to to use it because it will make your code more readable and easy to understand.

To initialize a Private type member, you can make use of custom constructor with parameters or properties.  An example for Private access modifier in C# is given below.

using System;



namespace Hello_World
{

    class Customer
    {
        private string _name; //Private field

        //Custom Constructor to Initialize Private Field
        public Customer(string name)
        {
            _name = name;
        }


        public void PrintName()
        {
            Console.WriteLine(_name);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Customer cust = new Customer("Robert Marks"); // Passing name as parameter to constructor
            cust.PrintName(); //Calling Public Method
        }
    }
}

 Output:

Robert Marks
Press any key to continue . . .