434 91 159KB
English Pages 74 [42] Year 2016
C# Programming
Quickly Learn C# Programming
Copyright © All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, without the prior written permission of the publisher. Disclaimer All the material contained in this book is provided for educational and informational purposes only. No responsibility can be taken for any results or outcomes resulting from the use of this material. While every attempt has been made to provide information that is both accurate and effective, the author does not assume any responsibility for the accuracy or use/misuse of this information.
Table of Contents C# Programming Table of Contents Introduction Chapter 1: C# 101 Chapter 2: First Program and Basic Syntax Chapter 3: Variables and Data Types Chapter 4: Operators Chapter 5: Conditional Statements Chapter 6: Loops Chapter 7: Understanding Methods Chapter 8: Using Arrays Chapter 9: Exception Handling Chapter 10: Inheritance Conclusion
Introduction It’s fascinating to see how numbers, letters, and symbols come together to power our computers. If you have always had an idea for a computer program, now is your time to learn to code. With C#, your dreams of becoming a programmer can become true. And they can do so without frustration as C# is easy to understand.
In this book, you will learn the basics of coding in C#. The book has been written in a way to be understood by even those with zero programming skills. If you have always thought that coding was difficult, this book will prove you wrong. Inside, there are lots of examples to deepen your understanding. And by the time you hit the last page, you should be able to create simple C# programs.
With that, we can get started. If you haven’t already, fire up your computer. And if you don’t understand some things at the beginning of the book, just keep going—things will make sense the further you go.
Chapter 1: C# 101 C#, pronounced as “C sharp,” is a general purpose object-oriented programming language. Some of its strengths are that it is easy to learn, creates efficient programs, and can be compiled on a number of systems. It is part of the .Net framework. And for this reason, some refer to it as the .Net language. C# was developed by Microsoft, thanks to one Anders Hejlsberg. With the name sounding like C and C++, you would expect C# to resemble those two aforementioned languages. And that is the case. But C# goes on to also mimic most of what Java has to offer. If you already have an understanding of C or C++, C# will prove to be easy. With C#, you have freedom to create programs that C, C++, Java, and other high-level programming languages can produce. You can create games, Windows applications, web applications, and apps for iOS and Android.
Setting Up the Right Environment In order to create C# programs, you need to have the right tools. Your computer is the most important tool in this environment. But you will also need other things on the software side. .Net Framework I already said that C# is part of the .Net Framework. As such, your computer needs this in order to execute C# code. If you are on a Windows computer, then you probably already have the .Net Framework. Integrated Development Environment (IDE) Microsoft offers Visual Studio (VS) as the IDE for creating C# applications and other languages like C++. With VS, you can create just about any kind of application you can imagine. VS can be downloaded from the Microsoft website for free. C# on Mac OS and Linux
The .Net framework is not available on Mac OS and Linux. Thankfully, there is an open-source alternative called Mono. And it comes with a C# compiler. Visit the Go Mono website for more on this.
Chapter 2: First Program and Basic Syntax Hello, Word! As with every programming language, we will get our hands wet with the Hello World program. Know that the examples in this book use Microsoft Visual C# 2010 Express, a trimmed version of Visual Studio.
First, launch Visual C#. Click File, select New Project, and then Console Application. In my case, this opens an editor in a file named Program.cs. Since there is some code in the editor, hit F5 to run it. A window will quickly open and close. That’s because the code does not have anything specific to do. We need to add more to it to create a “Hello World” program. Here is how that will look: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // my first program in C# Console.WriteLine("Hello, World!"); Console.ReadLine(); } } }
Notice the three lines I have added? The one in green, the one right below it, and the one that reads Console.ReadLine();. If you hit F5 again, you should get this output: Hello, World!
Explanation using System; using System.Collections.Generic; using System.Linq; using System.Text; using is a keyword employed to import a namespace. In this case, it imports the System namespace and other sub-namespaces of System. Now you may ask, what is a namespace? This refers to a construct that is used to organize code. Code that is similar in functionality is grouped together, ensuring that there is no conflict. The most important namespace is the System. namespace ConsoleApplication1 This line contains the namespace declaration, which in this case is ConsoleApplication1. class Program class is another keyword that introduces the class declaration. After the class keyword, you can then write the class name, which in this case is Program. Every program in C# needs at least one class. A class contains data and methods for your program. Code contained in a class must be enclosed in curly brackets. static void Main(string[] args) This is the entry point of this program, meaning this is the first piece of code the program will execute. static means that the method can be accessed without an instance of the class. And void means what the method will return, which in this case is nothing. Every program must contain a method called Main; otherwise, the program will not run. // my first program in C# This is a comment. And the compiler will ignore it. Comments can help you remember what your code does if you forget. And they will also tell others what you intend to achieve with your code. The double slash at the beginning means the comment is limited to one line. If you have a comment that takes several lines, write your comment inside the slashes (/*comments spanning several lines need to be formatted this way*/). Console.WriteLine("Hello, World!");
Console.WriteLine gives you the ability to output data in the console window. The data to display is enclosed in parentheses. Console.ReadLine(); When the program executes the Console.WriteLine statement, a console window will print “Hello, World!” Without Console.ReadLine, that window will close as quickly as it opens: you won’t even see your text. Console.ReadLine tricks your program into keeping the console window open until you provide an input, like pressing the Enter key. You might have noticed that our code contains blank lines and white spaces. These are there to make the code readable. You must know that C# is case sensitive. So Main and main are not the same. Also know that after every statement or expression, you must write a semicolon (;). If for some reason you do not want to use Visual C#, then you can code in a text editor. Here is how you can create a Hello World program: •
Copy the Hello World code into a text editor like Notepad.
•
Save the file as helloworld.cs
•
Open Command Prompt and navigate to where you saved your file.
•
Type csc helloworld.cs
•
If everything is right, command line will create an executable file of your program.
•
Type helloworld to run it.
Identifiers and Keywords Identifiers These are names you assign to namespaces, classes, variables, methods, etc. You can use letters, numbers, and underscores to create identifiers. However, an identifier can only begin with a letter or an underscore. If you would like to use a keyword as an identifier, then include @ at the beginning (e.g. @class). Here are other examples of valid identifiers: •
FIRST
•
first
•
fir_st
•
FirstName
•
\123names
Chapter 3: Variables and Data Types Variables are important in C# because you use them to store data (values). When assigning a value to a variable, you need to specify the data type of the variable. C# is a type-safe language, meaning it guarantees that each variable holds data of the appropriate type. Here is how to declare a variable: data_type variable_name; or data_type variable_name = value; The = sign is an assignment operator. And you will use it to assign values to variables. Here is how to declare a variable and assign a value later: static void Main(string[] args) { string message; // value assigned after variable declaration message = "Hello World!!"; Console.WriteLine(message); Console.ReadLine(); } string is the data type and message is the variable. The value that message holds is assigned in the line after the comment and that value is Hello World!!. But you can also declare a variable and assign it a value in the same line: static void Main(string[] args) { string message = "Hello World!!"; Console.WriteLine(message); Console.ReadLine(); } C# also allows you to assign a value to several variables like this: int a, b, c, d = 5;
And you can also make multi-line variable declarations by doing this: int a, b, c, d = 5; The compiler will read the above code as one line until it finds the semi-colon. You can as well declare a variable by assigning it to another variable: int r = 56; int y = r; // the value of y will also be 56 as a result Here is a fun program you can try. Copy it into the Visual C# editor and run it: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string firstname, lastname; Console.WriteLine("Enter Your First Name:"); firstname = Console.ReadLine(); Console.WriteLine("Now Enter Your Last Name:"); lastname = Console.ReadLine(); Console.WriteLine("Your name is " + firstname + " " + lastname); Console.ReadLine(); } } } Remember that Console.Readline() is meant to take input from the user. So whatever input the user enters will become the values of the variables firstname and lastname. Try changing the code and observe what happens; for example, delete the quotes and one plus sign between firstname and lastname in the line that prints your name.
Data Types
This chapter made it clear that before you declare a variable, you must specify its data type: data_type variable_name; From the examples above, you might have noticed string and int. But these are not the only data types. Let’s look at the most popular ones in detail: string: this is used for storing text. You can take Hello World as an example. When working with strings, be sure to place them in quotes. char: single unicode character. int: short for integer. As such, you use it to store whole numbers. Some examples are 5, 10, and 10003. float: this represents 32-bit single-precision floating point type. Its range is -3.402823e38 to 3.402823e38. double: this is 64-bit double-precision floating point type. And its range is -1.79769313486232e308 to 1.79769313486232e308. decimal: this stands for 128-bit decimal values with 28 to 29 significant figures. byte: this indicates an 8-bit unsigned integer. Its range is 0 to 255. sbyte: this represents an 8-bit signed integer. And the range is -128 to 127. uint: stands for a 32-bit signed integer and has a range of 0 to 4294967295. short: means a 16-bit signed integer. The range is -32,768 to 32,767. long: represents a 64-bit signed integer. ulong: indicates a 64-bit unsigned integer. bool: the simplest data type in C#. Its range consists of 2 values which are True and False. You will use it when writing logical expressions. DateTime: used to indicate date and time. If a value assigned to a variable is not in accordance with the specified data type, the compiler will show an error message. Try the following example: int x = 1; Console.WriteLine(x); Console.ReadLine(); Now try this wrong example: int x = "Program"; Console.WriteLine(x); Console.ReadLine(); Remember, int can only take whole numbers; Program is a string.
Chapter 4: Operators Operators instruct a compiler to perform a specific operation. For example, in the expression 5 – 3, the minus sign is the operator while 5 and 3 are operands. This expression tells the compiler to subtract 3 from 5. Below, we will look at the different types of operators available in C#.
1. Assignment Operators Here is a list of assignment operators you can use in C#: Operator =
Explanation The equals sign assigns a value to a variable.
Example a=7 b=x–y c = “Chris”
+=
This is Add AND. It adds the left operand to the right operand and makes the result the value of the left operand.
a += b means a = a + b
-=
This is Subtract AND. And it subtracts the right operand from the left operand to make the result the left operand.
a -= b means a = a - b
*=
Represents Multiply AND. It multiplies the left operand by the one on the right and places the result as the left operand.
a *= b means a = a * b
/=
This represents Divide AND. And it divides the left operand by the one on the right. The result becomes the left operand.
a /= b means a = a / b
%=
This is Modulus AND. It performs the Modulo on the left and right operands and makes the result the left operand.
a %= b means a = a % b;
> b
2. Arithmetic Operators These operators are useful in creating mathematical expressions. Here is a table for more (a = 1 and b = 2): Operator
Explanation
Example
+
This adds the operands involved.
a+b=3
-
This subtracts the right operand from the left operand.
b–a=1
*
This multiplies the right operand by the one on the left.
a*b=2
/
This operator divides the left operand by the right operand.
b/a=2
%
This performs a Modula on the left and right operands.
b%a=0
Here is a code you can use to try these operators: int a = 1; int b = 2; Console.WriteLine(b * a); Console.ReadLine(); Change the operator in Console.WriteLine(b * a) and observe what happens.
3. Logical Operators These are used to check if certain expressions are either true or false. Here is a table for more (a = true and b = false): Operator &&
Explanation This is Logical AND. It checks if both operands involved are True. If they are, it returns True. But if one or both is false, the expression returns False.
Example a && b will return false
||
This is Logical OR. It returns True if any of the operands is true.
a || b will return true
!
This is Logical NOT. And it invents the current value of a Boolean expression.
!(a && b) becomes true.
4. Relational Operators These operators are used to check if two operands involved in an expression are true or false. The table below shows the relational operators you can use in C# (a = 4, b = 10): Operator Explanation == This evaluates if the operands on either side of the operator are equal. If they are, it returns True.
Example a == b is false
!=
This means not equal to. It returns True if the operands on either side of the operator are not equal.
a != b is true
This is greater than. And it checks if the left operand is greater than that on the right. And if it is, it returns True.
b > a is true
= a is true
Chapter 5: Conditional Statements
if Statement This is one of the most important statements when coding. It allows you to specify an action a program should take if a certain condition is met. This means you need to specify the condition first. Your program will check if this condition is true, after which it will execute a specific action. But in case the condition is false, the program will not execute the body of the if statement. Here is the syntax of an if statement: if(boolean expression) { // execute this code block if expression is true } Here is an example to help you understand this: static void Main(string[] args) { int a = 5, b = 35; if (a >= b) { Console.WriteLine("a is greater than or equal to b"); Console.ReadLine(); } if (a 70) Console.WriteLine("Oops! The number can only be between 50 and 70."); else if (number < 50) Console.WriteLine("Oops! That's less than 50."); else Console.WriteLine("You got it. Yeah!!!"); Console.ReadLine(); }
The Switch Statement
If you have multiple conditions to check, you are free to use multiple if statements. However, this makes your code hard to read. And it’s also an inefficient way to run programs. Your best bet is to use the switch statement, which is similar to having multiple if statements. With this, you will create one switch statement and pair it with cases. Here is an example: static void Main(string[] args) { Console.WriteLine("Choose a color: blue, green, red, or orange."); string color = Console.ReadLine(); switch (color.ToLower()) { case "blue": case "green": case "red": Console.WriteLine("We have this in stock."); break; case "orange": Console.WriteLine("We don't have this color in stock."); break; } Console.ReadLine(); } Explanation of the above program: When creating switch statements, place the identifier, which in this case is the variable color, in front of the keyword switch. color can take any value. But in the above example, it can only take strings which have to be entered by the user. In the switch statement, .ToLower() tells our compiler to convert what the user inputs to lowercase. Remember, blue and Blue are different as far as C# is concerned. break is a keyword that’s used to stop the execution of a particular code block. switch statements allow you to add default actions. This means that if a user inputs something that’s not a case, the program will execute the default action. Here is an example of that. static void Main(string[] args) { Console.WriteLine("Choose a color: blue, green, red, or orange."); string color = Console.ReadLine(); switch (color.ToLower()) { case "blue": case "green": case "red": Console.WriteLine("We have this in stock."); break; case "orange": Console.WriteLine("We don't have this in stock."); break;
default: Console.WriteLine("Re-run the program and type the correct color."); break; } Console.ReadLine(); } With the default action, a user will get a nice message and not a blank line telling him or her what to do after entering an unrecognized string. You can think of yellow as an example.
Chapter 6: Loops You may want to repeat a certain part of your code several times. This means you would have to rewrite that code as many times as you want it repeated. However, that is inefficient. You can easily get around this problem with loops. Let’s discuss the different types you have at your disposal.
The While Loop This is the simplest of all loops. It executes your code as long as a condition you have specified in the while statement stays true. This means that if the condition evaluates true, the code block of the while statement will be executed. Then the program will recheck the condition, if it is still true, it will reexecute the code block of the while statement. This will go on until the condition evaluates to false. After this, the program will move on to the next line in your code. Here is an example: static void Main(string[] args) { int x = 0; while (x < 5) { Console.WriteLine("The value of x is {0} ", + x); x++; } Console.ReadLine(); } Output: The value of x is 0 The value of x is 1 The value of x is 2 The value of x is 3 The value of x is 4 In the above example, the while statement has been designed to check the value of x. If x is less than 5, its value should be printed on screen. x++ tells our program to look at the value of x at any given time and add 1 to it. You can alternatively write this as x = x + 1. In the first instance the while statement is run, x is equal to 0. Being less than 5, 0 is printed on screen. The program then returns to the while statement and checks x. This time, x is 1. So it is again printed on
screen. This goes on until x becomes 5, which makes the while statement return False. So the code block of the while statement is not executed and the program moves on to the next line (Console.ReadLine()). You might have noticed {0} inside the statement that prints the value of x on screen. The zero is a placeholder. And it represents the variable x, which is on position zero at the end of that same statement.
Do…While Loop This is the same as the while loop. The only difference is that in the Do…While loop, the code block is executed first and the condition is checked later. So your code gets executed at least once. Here is an example: static void Main(string[] args) { int x = 0; do { Console.WriteLine("The value of x is {0}", x); x++; } while (x < 6); Console.ReadLine(); } Try changing the value of x to 7 and observe what happens.
For Loop This is one of the most popular loops you can use. And it repeats your code for a specific number of times. Here is its syntax: for (initialize value; state condition; state increment/decrement) { statement(s); } Here is an example you can try: static void Main(string[] args) { for (int x = 0; x < 5; x++) { Console.WriteLine("Value of x: {0}", x); } Console.ReadLine(); } Output:
Value of x: 0 Value of x: 1 Value of x: 2 Value of x: 3 Value of x: 4 In the for statement, we have 0 as the value of x. x < 5 is a bool condition which will evaluate to True or False. And x++ adds 1 to the current value of x.
Foreach This works in the same way as for loop. foreach is best used when you want to loop items in an array. foreach is easier to read and less prone to errors than for loop. Here is an example: static void Main(string[] args) { string[] boyNames = new string[] { "John", "Emmanuel", "Fred", "Tom", "Mike" }; foreach (string Name in boyNames) { Console.WriteLine("Boy Name: {0}", Name); } Console.ReadLine(); }
Chapter 7: Understanding Methods We briefly looked at methods earlier in the book. In this chapter, we will dive deeper into this topic as it’s important. So far, the programs we have created have had our code go into the Main() method. There is no problem with this since most of them had single tasks to perform. But as your code grows, you will find it necessary to add other methods. Similar functions will be grouped together, making your code easier to read and reusable. You will also have a chance to hide some information and avoid duplication. When creating a method, ensure that you contain it in a class. And do not get carried away to include too many functions in the method—just one is enough.
How to Define a Method Here is the syntax you can use when specifying methods: AccessLevel ReturnValueType MethodName(ParameterList) { Statements } Access Level: this uses access modifiers to specify the visibility of a method. private means the method can only be seen by other elements in the same class. public refers to methods freely visible to everyone and everything. protected is for methods with their access restricted to the same class and derived classes. Return Value Type: a method can return a value. And you use data types to indicate the value a method should return. int, for instance, means the method will return an integer while void means it will return nothing. Method Name: this is just an identifier. And you must follow the rules used when making identifiers. Parameter List: this comes in a pair of parentheses. If you have more than one parameter, separate them with commas. Parameters pass and receive data to the method. If you have empty parentheses, it means you have no parameters. Statements: this is the code to be executed, and it’s enclosed in curly brackets. Here is an example on this: public void sampleMethod() { Console.WriteLine("My sample method has been called."); }
Calling a Method The above method (sampleMethod()) can be called from another method. Here is an example: using System; class Program { static void Main() { Console.WriteLine("This is the main method."); sampleMethod(); Console.ReadLine(); } public static void sampleMethod() { Console.WriteLine("My sample method has been called."); } } When the program executes the Main method, it will first display “This is the main method.” The next line, however, tells it to execute sampleMethod(). So the program will leave Main() and go to sampleMethod(). After it is done with it, it will go back to Main to execute Console.ReadLine(). You might have noticed that I have added static in the sampleMethod. That’s because I cannot call a non-static Method into a static one.
Popular Statements The Return Statement Methods can be coded to return values into other methods. Consider the below example: namespace ConsoleApplication1 { class Addition { static void Main() { addInt(10, 30); } static void addInt(int a, int b) { int c = a + b; Console.WriteLine("Adding {0} and {1} brings {2} as the answer.", a, b, c);
Console.ReadLine(); } } } In the above example, addInt is being called in the Main. We can rewrite this code to only return the result when addInt is called. Here is how our code will look like: namespace ConsoleApplication1 { class Addition { static void Main() { int result = addInt(10, 30); Console.WriteLine("The answer is {0}.", result); Console.ReadLine(); } static int addInt(int a, int b) { int c = a + b; return c; } } } The addInt method had to have its value changed from void to int, which stops it from returning nothing to returning integers. return c also had to be added in the statements, replacing the code that printed the answer on screen. Now that we have addInt returning a value to the method it is called from, we need to capture that return value in the Main method, which is where addInt is being called. The line that says int result = addInt(10, 30) accomplishes this. The break Statement This is one other important statement in C#. When you have a break in a certain code block, the program will terminate that code and move on to the next code block. Here is an example: namespace breakExample { class Program { static void Main(string[] args) { int a = 5; while (a < 15)
{ Console.WriteLine(a); if (a == 9) { Console.WriteLine("Break statement encountered."); break; } a++; } Console.ReadLine(); } } } In the above example, the program cannot display any numbers greater than 9 because it has been instructed to break once a becomes 9.
Chapter 8: Using Arrays An array is a collection of data of a similar type. Arrays can hold more than one item (also called element) at a time. Each of these items has an index representing it; for example, the index of the first item is 0 while the index of the second item is 1. Although you can use variables to hold data, arrays save time. Here is the syntax of an array: dataType[] arrayName; •
dataType represents the type of data an array can hold. This can be int, string, char, etc.
•
The square brackets indicate that this is an array.
•
The arrayName is just an identifier.
Declaring and Initializing Arrays When initializing an array, you must use the new keyword. Here is an example: int[] num = new int[5]; //This is how you declare a single-dimensional array The 5 in the square brackets indicates the number of values the array can hold. Such an array is said to be single-dimensional. Here is an example of a multi-dimensional array: string[,] couples = new string[3, 2]; // Declaring a multi-dimensional an array With multi-dimensional arrays, put a comma inside the first square brackets. The second bracket, as usual, indicates the length of our array: [3, 2] means we will have 3 pairs of couples. For a better understanding of this, let’s look at examples. We will start with the num array: int[] num = new int[5] { 1, 2, 3, 4, 5 }; //declaration and initialization at once Or we can rewrite it this way: int[] num = new int[5]; //this declares the array //this initializes the array num[0] = 1; //the 0 in the square brackets is the index num[1] = 2; num[2] = 3; num[3] = 4; num[4] = 5;
Now let’s look at how you can initialize a multi-dimensional array. We will use the couples array from above: string[,] couples = new string[3, 2] {{"John", "Loyce"},{"James", "Linda"},{"Vincent", "Mary"}};
Accessing Arrays To access an element in an array, use the index. For example, if I want to access the element at index 1, I need to put that index in square brackets just after the array name. Here is an example: static void Main(string[] args) { int[] num = new int[5]; //this declares the array //this initializes the array num[0] = 1; //the 0 in the square brackets is the index num[1] = 2; num[2] = 3; num[3] = 4; num[4] = 5; //accessing an array Console.WriteLine("The first number is {0}.", num[0]); Console.WriteLine("The second number is {0}.", num[1]); Console.WriteLine("The third number is {0}.", num[2]); Console.WriteLine("The fourth number is {0}.", num[3]); Console.WriteLine("The fifth number is {0}.", num[4]); Console.ReadLine(); } To access elements in a multi-dimensional array, here is a code you can use (copy and paste it just after the opening bracket of the Main method): string[,] couples = new string[3, 2] {{"John", "Loyce"},{"James", "Linda"},{"Vincent", "Mary"}}; //accessing an array Console.WriteLine("The first couple is {0} and {1}.", couples[0, 0], couples[0, 1]); Console.WriteLine("The second couple is {0} and {1}.", couples[1, 0], couples[1, 1]); Console.WriteLine("The third couple is {0} and {1}.", couples[2, 0], couples[2, 1]); Console.ReadLine();
Chapter 9: Exception Handling An exception is an error that occurs at runtime. Here is a popular example: assume you’ve created a program that returns a result after dividing two numbers that have to be entered by the user. Now imagine a situation where a user enters 0 as the other number. This will cause an error and the program will crash. Exception handling comes in to keep this from happening. If you employ it, the program will display a message about the error and continue running. To use exception handling, you need three important blocks of code: try, catch, and finally. But you may also add a fourth one called throw: •
try: this is a keyword. And it identifies a block of code which may cause an exception.
•
catch: this is also another keyword. And it handles the exception after try has raised it.
•
finally: this block of code is executed whether there is an exception or not.
•
throw: another keyword used to add user defined exception messages.
Let’s look at an example: static void Main(string[] args) { int num1, num2; decimal result; Console.WriteLine("This program divides two numbers"); Console.WriteLine("Enter the first Number: "); num1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the second Number: "); num2 = Convert.ToInt32(Console.ReadLine()); result = (decimal)num1 / (decimal)num2; Console.WriteLine("The answer is " + result.ToString()); Console.ReadLine(); } Copy this code into the editor and run the program. On your first try, input 4 as the first number and 2 as the second number. As you will see, you should have no troubles. Close the console and run the program again. This time, enter any number and 0. The program will crash, staining our coding abilities in the eyes of our users. Thankfully, we have exception handling. Here is a code that can save us from the embarrassment: static void Main(string[] args) { MainBlock: //This is the try block try
{ int num1, num2; decimal result; Console.WriteLine("This program divides two numbers"); Console.WriteLine("Enter the first Number: "); num1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the second Number: "); num2 = Convert.ToInt32(Console.ReadLine()); result = (decimal)num1 / (decimal)num2; Console.WriteLine("The answer is " + result.ToString()); } //This is the catch block to handle exception catch (DivideByZeroException dex) { Console.WriteLine("Entering 0 raises an exception!"); Console.WriteLine("Details about Error: " + dex.ToString()); goto MainBlock; } //This is the finally block finally { Console.ReadLine(); Console.WriteLine("Press Enter to close or reload the program"); Console.ReadLine(); } } After running the program, input any number and 0. This time, the program will not crash. Rather, it will display an error and allow you to rerun it by pressing Enter. Know that goto is a keyword that instructs a program to jump to a certain label in your code. In the above example, the label is MainBlock.
User-Defined Exceptions In C#, you can create your own exceptions. These are called user generated exceptions or custom exceptions. And they use the throw keyword we already talked about. Study this example: namespace userDefinedException { class Program { static void Main(string[] args) {
int maxR; Console.WriteLine("Please rate the last movie you just watched. The rating goes from 1 (very bad) to 5 (very exciting)."); maxR = Convert.ToInt32(Console.ReadLine()); try { if (maxR