Lesson 10.1

Private Access Modifier C# with Programming Example


Objective

What is private access modifier?
What is Get Set modifier?
Programming Example

What is Private Access Modifier?

private keyword is a member of Access Modifier. It is the top restricted access level. Private member cannot be called or cannot be accessed outside of its class declaration or struct declaration. You will get compile time error if you try to access private member directly outside the class.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace private_modifier
{
    class Salary
    {
        private int amount=5000;
        public int getamount()
        {
            return amount;
        }        
    }
    class Program
    {
        static void Main(string[] args)
        {
            Salary s = new Salary();
            //following code will raise access level error please don't uncomment it
            //int amt=s.amount;
            int amt = s.getamount();
            Console.WriteLine(amt);
            Console.ReadKey();

        }
    }
}

Output

5000
_

Explanation

In the above example there is a private variable amount which holds an integer value 5000. This variable cannot directly be accessed in other class. The only way to access private value using public method or using get set modifier.

Get Set Modifier

Get Set modifier is used for accessing private variable or storing value on private variable. Get Modifier returns a value and Set modifier set value to private variable. You can easily understand the concept of Get Set Modifier using the following programming example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Get_Set_Modifier
{
    class Account
    {
        private int amount;public int Amount
        {
            get
            {
                return amount;
            }
            set
            {
                amount = value;
            }
        }
        public int result()
        {
            int res = amount + 1000;
            return res;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Account ac = new Account();
            ac.Amount = 2000;
            Console.WriteLine(ac.result());
            Console.ReadKey();
        }
    }
}

Output

3000 _

Explanation

In the above example there is a private variable amount. This variable cannot be accessed directly outside the class so we have created Amount property using Get Set modifier. Get Set modifier set value to private variable amount and also retrieve value from private variable.

Summary

In this chapter you have learned what is private access modifier and how to use it in programming. You have also learned Get Set modifier and knew how to create property. The next chapter is explaining protected access modifier.

BackNext