HomeC# C# Simplified, part 2: Methods & Programmi...
C# Simplified, part 2: Methods & Programming Constructs
In this article, you will learn about methods, which perform actions and carry out funtions. You will also learn about programming constructs and looping statements in C#. This is the second article in a series covering C#; the first article in the series is available here.
C# Simplified covers each and every concept of the C# programming language in a concise manner. The articles in this series have been divided into several parts and will provide detailed explanations along with source code and screenshots. This series has been specifically written for beginners and students with an aim to teach C# in the quickest possible time. Please send your comments to csharpsimplified@gmail.com.
Methods
Methods are building blocks in C#. They perform some kind of action or carry out many functions such as printing, saving and opening a dialog box. The action could be anything, based on your application. For instance, the code for printing a report can be given inside a method. After declaring the method you can call it, preferably with a button event. You can also reuse this method with the help of inheritance. Inheritance is one of the features of any Object Oriented programming language such as C#.
There are basically two types of methods in C#. They are known as instance and class methods. Even though both methods perform the same work, there are differences in their declaration and usage. Methods can also be declared with parameters, and accessed by passing the required values.
Instance Method
The instance method is a method which is declared outside the Main() method. It can be accessed only by creating an object of the class, as in the case of an Instance Variable (see Listing 2.1).
Listing 2.1
using System;
class Instancemethod
{
//Method declared outside the main and hence Instance Method.
void show()
{
int x = 500;
int y = 700;
Console.WriteLine(x);
Console.WriteLine(y);
}
public static void Main()
{
//Object created
Instancemethod IM = new Instancemethod();
//Instance method called
IM.show();
}
}
In the above listing, a method named show() is declared, which prints the values of two variables. Inside the Main() method, an object of the class named IM is created and the method is called.
Class Method
A class method is also placed outside the Main() method with the exception that it should be declared with the keyword static. An interesting point to note is that class methods can be accessed without creating an object of the corresponding class. The general format for accessing a class method is C lassname.Methodname. Listing 2.2 illustrates the working of a class method:
Listing 2.2
using System;
class Classmethod
{
//A class method declared, notice the static keyword
static void show()
{
int x = 700;
int y = 900;
Console.WriteLine(x);
Console.WriteLine(y);
}
public static void Main()
{
/* Class method called without creating an object
of the class */
Classmethod.show();
}
}
In the above listing, a method named show() is declared, which prints the values of two variables. Inside the Main() method, the method is called without creating an object of the class. This is because of the static keyword, which we applied while declaring the method.
As explained earlier, you can declare methods with parameters. You can supply any number of parameters inside a method. The parameter should include a valid data type followed by a variable, as shown in listing 2.3.
Listing 2.3
void display(int x, int y)
{
//Statements goes here
}
An important point which you must keep in mind is that you have to supply relevant values while calling the method, as shown in listing 2.4. Otherwise, there will be compilation errors.
Listing 2.4
d.display(200,400);
The listing given below illustrates this concept with a help of a simple program.
Listing 2.5
using System;
class Params
{
// A Method named display() declared with two parameters x and y of type integer
void display(int x,int y)
{
Console.WriteLine(x);
Console.WriteLine(y);
}
public static void Main()
{
//Object of the class created
Params prm = new Params();
//Method display() called by passing two integer values
prm.display(700,900);
}
}
In the above listing, a method named display() is declared with two integer parameters. The method also gives necessary statements for printing the value of those variables. Note that we haven't given any value to the variables while declaring the method. Inside the Main() method, an object of the class is created, and the method display() is called by passing two values. If you are not passing any values while accessing the method, there will be compilation errors.
In listing 2.5, we declared a single method named display(). This method contains two integer parameters. You can also declare the same method once again in the same class, but it should contain different parameters. This process is known as Method Overloading.
If you attempt to declare the method with the same parameter, then the C# compiler won't know which one is the correct method, and there will be compilation errors. Listing 2.6 declares two methods named display(). The first method is declared with one integer parameter and the second one with two integer parameters. Inside the Main() method, show() method is called by passing the respective values.
Listing 2.6
using System;
class Methodover
{
//Method display() declared with one integer parameter
void display(int x)
{
Console.WriteLine(x);
}
//Method display() declared with two integer parameters
void display(int a, int b)
{
Console.WriteLine(a);
Console.WriteLine(b);
}
public static void Main()
{
//Object of the class created
Overloadmethod over = new Overloadmethod ();
//display() Method called by passing respective values
Like all other programming languages, C# also offers programming constructs, namely if-else and switch-case. The usage of these constructs is similar to that of their Java and C++ counterparts, and is explained below in detail.
If-else
This is the popular decision making statement used in C#. It helps you to compare between two or more values. Its usage is shown in listing 2.7.
Listing 2.7
if(Condition)
{
Statements
}
else
{
Statements
}
In listing 2.8, two values are compared. If the value of X1 is greater than X2, the message "X1 is greater" will be displayed. Otherwise, the statement inside the else part will be printed as output.
Listing 2.8
using System;
class CompareIfElse
{
public static void Main()
{
int X1 = 50;
int X2 = 100;
if(X1>X2)
{
Console.WriteLine("X1 is greater");
}
else
{
Console.WriteLine("X2 is greater");
}
}
}
switch-case
This construct is also intended to be used for decision making, but it is generally regarded as an alternative to the if-else clause discussed above. This construct will be particularly useful for large programs, because it is difficult for the developers to debug several if-else branches. Its usage is shown in listing 2.9.
Listing 2.9
switch(expression)
{
case X:
Console.WriteLine("X is selected");
break;
case Y:
Console.WriteLine("Y is selected");
break;
default:
Console.WriteLine("Invalid Selection");
break;
}
When the expression matches with a case value, the respective statements will be printed. In listing 2.10, a value is declared as an integer type and its variable name is passed as a parameter to the switch() clause. The C# compiler looks for the relevant case entry. If it is found, the statements inside that case clause will be printed. If there is no valid case structure, the statements inside the default clause will be printed.
In the previous session, you have learned about decision making statements such as if-else and switch-case. C# offers a set of looping constructs with which you can perform certain tasks such as the printing of numbers from 1 to 30, or printing only the even/odd numbers. There are basically three types of looping constructs. For, while and do-while are explained in detail below.
for Loop
This loop is used to iterate a value for a fixed number of times. You should be very careful while using this loop, as incorrect usage might result in an infinite loop and crash the application. Its usage is given below:
The increment and decrement operators can be specified using either the ++ or - operators. In listing 2.11, a loop is created which will print numbers from 1 to 10. Since I have applied the <= operator, the number 10 will also be printed. If you apply the < operator, only 9 will be printed.
Listing 2.11
using System;
class ForLoop
{
public static void Main()
{
for(int I = 1; I<=10;I++)
{
Console.WriteLine(I);
}
}
}
while Loop
This looping construct is very similar to the for construct discussed above. The only exception is that the condition is specified first, and the loop will continue to execute as long as a particular condition is true. Its usage is shown below:
Usage
while(Condition)
{
Statements
}
If the specified condition is false, the statements within the loop won't execute. Listing 2.12 is a modified version of listing 2.11. But the resulting output will be different, as numbers from 2 to 11 will be printed. Here you have to declare the variable and increment/decrement operators separately, as shown in listing 2.12.
Listing 2.12
using System;
class WhileLoop
{
public static void Main()
{
int I = 1;
while(I <=10)
{
I++;
console.WriteLine(I);
}
}
}
do-while Loop
This looping construct is also similar to that of the while loop, but the condition is specified last, and after closing the do construct. Its usage is given below:
Usage
Do
{
Statements
}
while(Condition)
As explained above, the condition is tested at the end of the loop. Hence, the statements within the loop are executed at least once even if the condition is false. In listing 2.13, numbers from 1 to 11 will be printed. If you change the condition to greater than, then the loop will execute once.
This statement is used to terminate a loop abruptly. You have already seen the usage of this statement while discussing the switch-case construct. If the condition is true and the compiler finds a break statement, then the program will stop at that point. In listing 2.14, a loop is created to print numbers from 1 to 10. But since I have specified the break statement inside an if clause, the program will terminate after printing the numbers from 1 to 5.
Listing 2.14
using System;
class Breaks
{
public static void Main()
{
for(int I = 1; I<=10; I++)
{
Console.WriteLine(I);
if(I==5)
{
break;
}
}
}
}
Summary
In this part of the series, you have seen the working of different types of methods with the help of relevant source codes. The article also discussed the various programming constructs, including the different lopping statements such as for, while, do-while, and so forth. In the next article, you will learn about the different escape characters and other important topics, such as arrays.