Classes and Methods in C# - C# FOR BEGINNERS CRASH COURSE (2014)

C# FOR BEGINNERS CRASH COURSE (2014)

Chapter 8 Classes and Methods in C#

8.1 Class declaration

In C# classes are the primary building blocks of the language. It provides predefined set of variables and methods. Objects are defined as an instance of a class, therefore the methods inside the class determine what can be executed on the object.

Class Definition

A class definition starts with keyword class followed by the actual class name. The class variables and methods are all enclosed in between the curly brackets; this area is also called the class body.

Syntax:

<access specifier>class class_name

{

//member variables

<access specifier> <data type> variable1;

<access specifier> <data type> variable2;

……

<access specifier><data type> variableN;

//member methods

<access specifier><return type>method1(parameter_list)

{

//method body

}

<access specifier><return type>method2(parameter_list)

{

//method body

}

….

<access specifier><return type>methodN(parameter_list)

{

//method body

}

}

· Access specifiers define the level of contact for other methods and members to be able to interact with methods and members of the given class. If no access specifier is specified, the default access specifier is private.

· The date type specifies the variable type and the return type is used to state what type of data is returned from the method, although it should be noted that a method does not need to always return anything.

· The dot(.) operator is used for accessing the class member

· The dot operator is used to link the object name and member name

Example to demonstrate class

Example 18:

using System;

namespace demo

{

class Calculate

{

public int len;

public int bread;

}

class Program

{

static void Main(string[] args)

{

Calculate c1 = new Calculate();

Calculate c2 = new Calculate();

int area = 0;

int area1 = 0;

c1.len = 10;

c1.bread = 5;

c2.len = 15;

c2.bread = 10;

area = c1.len*c1.bread;

Console.WriteLine("area of rectangle1 is:{0}",area);

area1 = c2.len*c2.bread;

Console.WriteLine("area of rectangle2 is:{0}",area1)

Console.ReadLine();

}

}

}

When compiled the result of this class will be:

area of rectangle2 is:50

area of rectangle2 is:150

C# constructors

A constructor is a special type of method invoked automatically when the instance of the class is created. The members of the class are initialized inside the constructors. The constructor has to have the same name as the class itself.

Example of Constructor

Example 19:

using System;

namespace construct

{

class Calculate

{

int number1,number2,sum;

Calculate()

{

number1 = 20;

number2 = 40;

}

public void Addition()

{

sum = number1+number2;

}

public void Show()

{

Console.WriteLine("The total is:{0}",sum);

}

public static void Main(string[] args)

{

Calculate c1 = new Calculate();

c1.Addition();

c1.Show();

}

}

}

When compiled the result of this class will be:

The total is: 60

In the example above every time the classCalculateis instantiated, the constructor manually assigns a fixed value tonumber1andnumber2. However what if you wanted to make the values ofnumber1andnumber2 different and dynamic? How would this be achieved?

Well this is where a concept of a parameterized constructor comes in. Essentially what this fancy term means is that we pass in parameters directly in to the constructor, this allows us to pass in values at the point of instantiation of the class. Lets look at an example:

Example of parameterized constructor

Example 20:

using System;

namespace construct

{

class Calculate

{

int number1,number2,sum;

// Parameters are added in to here inside the constructor

Calculate(int num1,int num2)

{

// We assign the parameters to the class variables

number1 = num1;

number2 = num2;

}

public void Addition()

{

sum=number1+number2;

}

public void Show()

{

Console.WriteLine("The total is:{0}",sum);

}

public static void Main(string[] args)

{

int a,b;

Console.WriteLine("Enter value of a");

a = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the value of b");

b = Convert.ToInt32(Console.ReadLine());

// a and b are passed through to the class constructor

Calculate c1 = new Calculate(a,b);

c1.Addition();

c1.Show();

Console.ReadLine();

}

}

}

When compiled the result of the class is:

Enter value of a

10

Enter value of b

20

The total is: 30

C# destructors

A destructor is a special function in a class that is used very rarely to usually release unmanaged resources before exiting the class. The destructor has several limitations on how it can be used:

· It cannot be inherited.

· It cannot be overloaded.

· There can only be one destructor in any given class.

· The destructor cannot be directly called by the programmer; it is instead called by the Garbage Collector.

Destructor has the same name as its class and is prefixed with ~ symbol which is represented by a tilde.

Example of Destructors

Example 21:

using System;

namespace destruct

{

class Calculate

{

int number1,number2,sum;

Calculate()

{

number1=15;

number2=4;

}

public void Addition()

{

sum=number1+number2;

}

public void Show()

{

Console.WriteLine("The total is:{0}",sum);

}

// Destructor is defined here and is called when the class

// goes out of scope.

~Calculate()

{

Console.WriteLine("Destructor invoked");

}

public static void Main(string[] args)

{

Calculate c1=new Calculate();

c1.Addition();

c1.Show();

}

}

}

When compiled the result of the class will be:

The total is: 19

8.2 Defining methods

Method is a set of one or more program statements, which can be executed by calling the method name. For using a method, the user first needs to define a method and then call the method.

Defining a method means declaring the element of its structure. The following syntax is used for defining the method.

<Access Specifier> <Return Type> <Method Name> ( Parameter List)

{

Method Body

}

The different elements of a method are:

· Access specifier: It checks the extent to which the variable or method can be accessed.

· Return Type: This defines what the type is for the value returned by the method. If the type is set as void then this would mean that the method does not return anything.

· Method Name: It is a unique identifier and case sensitive. The method name cannot be the same as a variable name.

· Parameter List: The values that are passed and received by the method. After the method name, they are written in parentheses.

· Method Body: The set of instructions for performing the function of the actual method.

Example:

Example 22:

class Average

{

public int Number(int no1, int no2)

{

int output;

output = no1+no2/2;

return output;

}

}

8.3 Calling methods

Once the method is defined, a user can call the method using the method name. The method name is followed by the parentheses.

Example:

Example 23:

using System;

class Average

{

public int Number(int no1, int no2)

{

int output;

output = no1+no2/2;

return output;

}

static void Main(string[] args)

{

Average a = new Average();

// calling method Number from object class a

int value = a.Number(20,30);

Console.WriteLine("The result is {0}",value);

}

}

When the code is compiled the result is:

The result is 25

8.5 Recursive method call

A method can call itself this is known as recursion.

Example 24:

using System;

namespace recursive

{

class recursivecall

{

public int factorial(int no)

{

int result;

if(no == 1)

{

return 1;

}

else

{

result = factorial(no-1)*no;

return result;

}

}

static void Main(string[] args)

{

recursivecall r = new recursivecall();

Console.WriteLine("Factorial of no is {0}",n.factorial(2));

Console.WriteLine("Factorial of no is {0}",n.factorial(3));

Console.Read();

}

}

}

When the code is complied the result will be:

Factorial of no is 2

Factorial of no is 6

8.4 Passing parameters to method

When a user calls a method, if the method accepts parameters then these will have to be passed through at the time the method is called. There are three types of parameters passed to the method.

Value parameter

With a value parameter, the method creates a copy of this passed in parameter as a variable for use inside the method. If the value of this variable is changed, it will be only changed in the scope of the method itself and not of the original variable that was passed in as a parameter to the method.

Example:

Example 25:

class Program

{

void Increaseno(int no)

{

no++;

}

public static void Main()

{

Program p = new Program();

int number = 2;

p.Increaseno(number);

Console.WriteLine(number);

}

}

When the code is complied the result will be:

2

Reference Parameter

The reference parameter is the same as the value parameter except that when the parameter is passed to the method, instead of creating a copy of the parameter value, it instead directly points to the original stored value in memory. Thus, if the value is changed in the scope of the method then it will also change the value of the original variable that was passed in as a parameter.

The ref keyword is used for declaring the reference parameter.

Example:

Example 26:

class Program

{

void Increaseno(int no)

{

no++;

}

public static void Main()

{

Program p=new Program();

int number = 2;

p.Increaseno(ref number);

Console.WriteLine(number);

}

}

When the code is complied the result will be:

3

Output parameter

The return statement is used for returning value from the method. Only a single variable can be returned using return statement. The output parameter provides this purpose.

They are similar to reference parameters, except they transfer data out of the method.

Example:

Example 27:

class Program

{

void Demo(out int no)

{

no=10;

}

public static void Main()

{

Program p=new Program();

int number;

p.Demo(out number);

Console.WriteLine(number);

}

}

When the code is complied the result will be:

10