C# Private Access Modifier

In this chapter you will learn:

  1. Use Properties to get and set private member variable
  2. private static and const Fields
  3. Using Methods to change private fields

Use private access modifiers


/* www  . j a  v a  2s  . c o  m*/
using System;

class Circle{
    private int radius;
    
    public int Radius{
        get{
            return(radius);
        }
        set{
            radius = value;
        }
    }

}
class MainClass
{
    public static void Main()
    {
        Circle c = new Circle();
        c.Radius = 35;
    }
}

The code above generates the following result.

private static and const Fields

private static and const Fields


using System;/*from  w  w w  .  j a  v a2 s .c om*/

class MainClass
{
    static void Main(string[] args)
    {
        MyTV tv = new MyTV();
    }
}
public class MyTV
{
    public MyTV()
    {
        channel = 2;
    }
    private static int channel = 2;
    private const int maxChannels = 200;
}       

The code above generates the following result.

Using Methods to change private fields

The private field can only be changed through methods in the same class. The following code shows how to update private fields through methods.


using System;/*  w w w  . j av  a2  s.c  o  m*/

class Class1
{
  static void Main(string[] args)
  {
        MyCar car = new MyCar();
        int refChan = 0;
    int chan = 0;

        car.GetSpeed( chan );
        car.GetSpeed( ref refChan );
  }
}
public class MyCar
{
       private static int speed = 2;
       private const int maxSpeed = 200;
       
       public bool ChangeSpeed(int newSpeed)
       {
           if( newSpeed > maxSpeed )
               return false;

           speed = newSpeed;

           return true;
       }
       public void GetSpeed( int param )
       {
           param = speed;
       }

       public void GetSpeed( ref int param )
       {
           param = speed;
       }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Public vs private access
Home »
  C# Tutorial »
    C# Types »
      C# Access Modifier
C# Access Modifiers
C# Private Access Modifier
C# Public Access Modifier
C# Protected Access Modifier
C# Internal Access Modifier