C# Classes - Public and Private variables



In some cases we want to have ability to modify the value of a variable from outside the class. To do this we precede the variable name with public keyword.

Let us take a look at the following code

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

class Rectangle
{
    public int length, breadth;
    private int area;    
  
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }

}

namespace ClassRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            int area1;
            
            Rectangle rect1 = new Rectangle();
            rect1.length = 10;
            rect1.breadth = 20;
            area1 = rect1.calculatearea();
            Console.Write("Area of Rectangle is ");
            Console.WriteLine(area1);
            Console.ReadLine();
        }
    }
}

If you run the above program you should be able to see the same output as the previous program.

	
Area of Rectangle is 200



The difference is, this time we are able to assign the values of the variables of the class from the outside of the class. If you declare the variable as private, as in the following code it will report error.

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

class Rectangle
{
    private int length, breadth;
	 // Note that you can not assign the value of length and breadth out of class.
    private int area;    
  
    public int calculatearea()
    {
        area = length*breadth;
        return (area);           
        }

}

namespace ClassRectangle
{
    class Program
    {
        static void Main(string[] args)
        {
            int area1;
            
            Rectangle rect1 = new Rectangle();
            rect1.length = 10;  // Reprts error 
            rect1.breadth = 20;  // Reports error
            area1 = rect1.calculatearea();
            Console.Write("Area of Rectangle is ");
            Console.WriteLine(area1);
            Console.ReadLine();
        }
    }
}



If you declare a variable private within a class, the only way to change or assign its value is from within the class.If you do not assign any thing public or private, by default it assumes them to be private.

It is possible to assign the (default) values of some classes as soon as their instances are created. This is called constructor. We wil read them in the next page.