Book Store  
  Contact Us  
  Links  
  Site Map  
C# Tutorials - descision making

Classes in C#

 

Classes are fundamental to C# and introduce ways to represent real world and abstract concepts. A class is a classification which groups together variables and methods into reusable code blocks.

public class Box
{
....................
}

This is a definition of a class called Box and we can use it to represent a box object.

Classes include a number of code concepts :

  • Data members
  • Class instances
  • Public Fields
  • Properties
  • Class methods
  • Constuctors
  • Destructors

Data members

Data members or Fields allow you to store values inside the class and which are applicable to the class.

public class Box {

public double Height;
public double Width;
public double Depth;
}

Note that the Box class have been given the modifier of public which means that they CAN be accessed from outside the class.

Creating an instance of a class

To instantiate, or create an instance of a class we do the following:

Box LargeBox = new Box();

The keyword new creates a new instance of the Box class and assigns it to the LargeBox in the above example.

Assessing Public Fields

As we have made the fields public we can access the fields in the following way :

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Box LargBox = new Box();

            double Volume;

            Console.WriteLine("Height of box :");
            LargBox.Height = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine("Width of box :");
            LargBox.Width = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine("Depth of box :");
            LargBox.Depth = Convert.ToDouble(Console.ReadLine());

            Volume = LargBox.Height * LargBox.Width * LargBox.Depth;
            Console.WriteLine("Volume {0} :", Volume);

        }
    }
    
    public class Box
    {
        public double Height;
        public double Width;
        public double Depth;
    }

}

This example reads in the values for Height, Width and Depth, placing them into the public field values and then calculating the volume of the box.

Properties

The problem with the above example which uses public fields is that they may be accessed directly and it is possible for incorrect values to be entered. We can use the class to validate user input before it tries to store the values. We can also make the fields private so that they cannot be accessed directly.

using System;

namespace private_fields
{
    class Program
    {
        static void Main(string[] args)
        {

            Box myBox = new Box();

            myBox.Height = 10.20;
            myBox.Width = 13.10;
            myBox.Depth = 10.9;

            Console.WriteLine("Volume : {0}", myBox.Volume());
            
        }
    }


    public class Box
    {
        private double height;
        private double width;
        private double depth;


        public double Height
        {
            get
            {
                return Height;
            }
            set
            {

                if (value <= 0)
                {
                    height = 10;
                }
                else
                {
                    height = value;
                }
               
            }
        }


        public double Width
        {
            get
            {
                return width;
            }
            set
            {

                if (value <= 0)
                {
                    width = 10;
                }
                else
                {
                    width = value;
                }

            }
        }


        public double Depth
        {
            get
            {
                return Depth;
            }
            set
            {

                if (value <= 0)
                {
                    depth = 10;
                }
                else
                {
                    depth = value;
                }

            }
        }


        public double Volume()
        {
            return height * width * depth;         
        }

        
    }

}

In the above example,

  • the public definitions of Height have been changed to private and the name has changed to height
  • the new public definition for Height has been created and has validation included in the code

The public definitions include get and set. The get section is used to retrieve the value of the definition and the set section is used to set the value of the definition.

Class methods

C# is an object orientated programming language which supports encapsulation. Encapsulation means that all the methods and fields associated with the class are part of the class.

So in the example above the Volume calculation is done within the class itself. Doing it that way means that we can change the operation of the volume calculation without having to change the external code.

The class method of Volume in the above example is known as a method in the object orientated language.

Passing parameters

The class methods are able to have parameters to passing formation into the method as shown in the example below.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

	myMathsCals multi = new myMathsCals();

	Console.WriteLine("The answer is {0} ", multi.MultiplyNumbers(3,6));
	Console.WriteLine("The answer is {0} ", multi.MultiplyNumbers(3.3, 6.4));
	Console.WriteLine("The answer is {0} ", multi.MultiplyNumbers(3.3, 6.4, 4.3));
                      
        }
    }

    public class myMathsCals
    {

        public double MultiplyNumbers(int a, int b) 
        {
            return a * b;            
        }

        public double MultiplyNumbers(double a, double b)
        {
            return a * b;
        }

        public double MultiplyNumbers(double a, double b, double c)
        {
            return a * b * c;
        }


    }
}

In the above example we have created a method which has two parameters that are passed into the method.

Method Overloading

The above example also illustrates method overloading.

The first method MultiplyNumbers(int a, int b); uses integers as input values.

If a floating point value was passed in, it would generate an exception. However, we can have many version of MultiplyTwoNumbers each with a different interface : MultiplyNumbers(double a, double b); and MultiplyNumbers(double a, double b, double c);

Static methods

If you declare a class method as static it means that you do not have to create an instance of the class object. This is used for situations where the class is general and we don’t want to mess around creating objects.

If we look at the square root method which is part of the build in C# Math class, we can do Maths.Sqrt(57) where we do not have to create an instance of the Math class before we use it.

We can replicate this ourselves by defining the method as static

public static int MultiplyNumbers(int a, int b) { return a * b; }

In this case we can use this method without creating an instance of the class as follows:

double answer = myMathsCals.MultiplyNumbers(3,5);

Constructors

Constructors allow you to initialise the private data fields in the class.

The following example shows two constructors. The constructor as the same name as the class and must be public. The first constructor is called the default constructor and will run automatically whenever you create a new instance of the class. The second constructor allows you to pass parameters to the class and give you more scope for code re-use.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Box myBox = new Box(23.3, 12.4, 10.2);
            Console.WriteLine("Volume {0} : ", myBox.Volume());
        }
    }

    public class Box
    {
        private double height;
        private double width;
        private double depth;


        public Box()
        {
            height = 10;
            width = 10;
            depth = 10;
        }

        public Box(double h, double w, double d)
        {
            height = h;
            width = w;
            depth = d;
        }

        public double Height
        {
            get
            {
                return Height;
            }
            set
            {

                if (value <= 0)
                {
                    height = 10;
                }
                else
                {
                    height = value;
                }

            }
        }


        public double Width
        {
            get
            {
                return width;
            }
            set
            {

                if (value <= 0)
                {
                    width = 10;
                }
                else
                {
                    width = value;
                }

            }
        }


        public double Depth
        {
            get
            {
                return Depth;
            }
            set
            {

                if (value <= 0)
                {
                    depth = 10;
                }
                else
                {
                    depth = value;
                }

            }
        }


        public double Volume()
        {
            return height * width * depth;
        }


    }
}

 

Always include a default constructor and one which sets all the parameters as a minimum.

You can create other constructors as required.

Destructors

A constructor runs when an object is created from a class. A destructor is run when an object is destroyed. In C# a destructor is not as important as in C++ because memory is cleared automatically using garbage collection. A destructor is identified using ~ as follows :

~Box() { Console.WriteLine("Destructor has run"); }