Hi and welcome to the Lesson 5 – Methods, Exception Treatments, Classes and Object-Oriented on our tutorial series Learning C# with Zenva.
Tutorial Source Code
All of the source code for this tutorial can be downloaded here.
A method is a group of statements that together not only perform a task but also help to organise our code. Every C# program has at least one class with a method named Main. A class is where you will organise your methods and variables. In this lesson, we will discuss more about it. When we first create a new project, the project comes with a class called Program and a method called Main(), have you noticed it? In this lesson, we are going to learn how to define methods and use them, handle exceptions and treat them using the command “try”.
Before we start, remember back in Lesson 2, I said about access modifiers. They suit for both variables and methods. Let’s understand them. The three most used are:
Public: visible for all classes.
Private: visible to the class they belong.
Protected: visible to the class they belong and any subclass.
When we do not specify our modifier, by default it is private.
Defining Methods
A Method has the following syntax:
<access specifier> <Return type> <Method name> (Parameter List) { Method body }
Each method has his own signature, that is, name and parameters. I can have two methods with the same name but different parameters. This includes a number of parameters and type.
Let’s start a new project, choose console application and name it MethodsAndException. Write or copy and paste the code below.
First example: Adding two numbers.
using System; namespace MethodsAndException { public class Program { //method is static because I am calling it from the static method Main public static void SumTwoNumbers(int number1, int number2) { Console.WriteLine(number1 + " + " + number2 + " = " + (number1 + number2)); } public static void Main(string[] args) { int n1, n2; Console.WriteLine("Give me two numbers and I give you their sum!"); Console.Write("What is your first number: "); n1 = Convert.ToInt32(Console.ReadLine()); Console.Write("What is your second number: "); n2 = Convert.ToInt32(Console.ReadLine()); //calling the method. //SumTwoNumbers(n1, n2); Console.Read(); } } }
Understanding new code:
In this example, I made my class and methods public. The method SumTwoNumbers receives as parameters two integers, number1, and number2. It has on its return type, void, that is, the method does not return a value. This method simply sums the two numbers and shows on screen. Note that I am doing the operation in the message itself. I could create a variable to receive the sum and then write this variable, “result” for example, in the message. To call a method, we write its name and provide the parameters needed.
Second example: Who is greater?
using System; namespace MethodsAndException { public class Program { ////method is static because I am calling it from the static method Main //public static void SumTwoNumbers(int number1, int number2) //{ // Console.WriteLine(number1 + " + " + number2 + " = " + (number1 + number2)); //} //method return is a bool value (true or false) public static bool WhoIsGreater(int A, int B) { if (A > B) return true; else return false; } public static void Main(string[] args) { //int n1, n2; //Console.WriteLine("Give me two numbers and I give you their sum!"); //Console.Write("What is your first number: "); //n1 = Convert.ToInt32(Console.ReadLine()); //Console.Write("What is your second number: "); //n2 = Convert.ToInt32(Console.ReadLine()); //calling the method. //SumTwoNumbers(n1, n2); if (WhoIsGreater(10, 5)) //if is true than A > B. Here you can change values for testing. { Console.WriteLine("A is greater than B"); } else { Console.WriteLine("A is greater than B"); } Console.Read(); } } }
The method WhoIsGreater also receives two parameters (integer), A and B. This method verify if A is greater than B and return true if condition applies or false if B is greater than A. In this case, we set return type as bool, that is, returns a Boolean value(true or false).
Running our applications:
Exception Treatments
What if, instead of a number, the user types a word or some character that is not a number? An exception would occur:
What is happening is: we are trying to convert a char to number, which is kind impossible. To handle this exception and many others, we use the command “try”. Let’s understand.
try { } catch (Exception) { throw; }
We try to do something. If an exception occurs, it goes directly to “catch” and we can show a message to the user. So, let’s put our code where we try to convert what the user type to int, inside the try-catch.
try { Console.WriteLine("Give me two numbers and I give you their sum!"); Console.Write("What is your first number: "); n1 = Convert.ToInt32(Console.ReadLine()); Console.Write("What is your second number: "); n2 = Convert.ToInt32(Console.ReadLine()); //calling the method. SumTwoNumbers(n1, n2); } catch (Exception) { Console.WriteLine("This is not a number!"); }
Now, our exception is treated!
Classes and Object-Oriented
A class consists of a group of variables, methods, and events that together enables you to create a construct by grouping these items. A class is simply a representation of an object type. It is like a structure that describes an object. By the way, an object is basically a block of memory that has been allocated and configured in accordance with the model. A program can create multiple objects of the same class. The object orientation is a bridge between the real world and the virtual, from this, it is possible to transcribe the way we see real world elements to our source code, in order to enable us to build complex systems based on objects.
Before we follow the example, let’s start a new project, choose console application and name it ClassesAndObjects, write or copy and paste the codes below.
So, let’s think about a person. A person has some attributes. In our case, we will create the followings: first name, last name, and age. With what you learnt until now, our code would look like this:
namespace ClassesAndObjects { public class Program { public static void Main(string[] args) { string firstname, lastName; int age; } } }
But what if we need to add one more person? New variables, firstName2, lastName2, age2? What about 5, 10, 100 records? Let’s create a class!!
namespace ClassesAndObjects { public class Person { public string firstName { get; set; } public string lastName { get; set; } public int age { get; set; } } public class Program { public static void Main(string[] args) { } } }
Note that, when we are programming object-oriented, we do not use fields as our variables. We now use Property.
A Property is a member that provides flexible ways to read, write, or compute values of fields. A get property accessor is used to return the property value, and a set accessor is used to assign a new value.
Tip: To write a property, try writing prop and press ‘tab’ twice.
Ok, but now, how to have access to these properties of this class? We create an object! To create an object, we need to instantiate the class and by doing that, we now have access to the class properties and methods. By pressing “dot” on my object p type Person(class), it shows all methods and properties accessible of this class.
Let’s set some values and show these values in our application.
using System; namespace ClassesAndObjects { public class Person { public string firstName { get; set; } public string lastName { get; set; } public int age { get; set; } } public class Program { public static void Main(string[] args) { //declaring a variable type Person (class) Person p = new Person(); p.firstName = "Alex"; p.lastName = "Wilson"; p.age = 37; Console.WriteLine("Hi, my name is "+ p.firstName +" "+ p.lastName + ". I am "+ p.age +" years old."); Console.Read(); } } }
Running our application:
Now if you want a new Person, it is easy. Just create new objects of Person with different names, for instance, p2, p3, p4… as you want.
Note that our message is full of ” “ and +. We certainly can get confused when we have to show a lot of information. So, there are two ways to show the same message:
Using format: We can use {n} to determine the quantity of our variables.
Console.WriteLine("Hi, my name is {0} {1} {2} years old.", p.firstName, p.lastName, p.age);
Now with C# 6.0 we can write like this: We put a $ before the string, so ‘{ }’ are not recognised as part of the string and yes a property.
Console.WriteLine($"Hi, my name is {p.firstName} {p.lastName} {p.age}");
As I said, classes also can have methods. So let’s create a method to check age of majority.
public class Person { public string firstName { get; set; } public string lastName { get; set; } public int age { get; set; } public string AgeOfMajority(int age) { if (age >= 18) return "You are of legal age!"; else return "You are not of legal age!"; } }
Now let’s receive the user age and check if the user is of legal age by calling the method AgeOfMajority();
Person p2 = new Person(); Console.Write("How old are you? "); int myAge = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(p2.AgeOfMajority(myAge));
Running our program:
This is our last tutorial about learning Basic C# . I hope you have enjoyed.
Thank you!