How to use private access modifiers

Use private access modifiers


/*from w  w w.jav a 2 s . co  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;//  w  w  w.ja  v  a  2s  .co  m

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 .  ja  v  a2  s. com*/

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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor