c# programming for human beings - · pdf filec# basic – lesson 1: installing visual...
TRANSCRIPT
C# Programming for
Human Beings
Allan Carlos Claudino Villa
© Zenva Pty Ltd 2016. All rights reserved
https://zenva.com
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 2
Table of Contents
C# Basic – Lesson 1: Installing Visual Studio and say “Hello World”! ....................................................3
C# Basic – Lesson 2: Operators, Variables and Data Types. ................................................................ 11
C# Basic – Lesson 3: Flow Control in C# ............................................................................................. 19
C# Basic – Lesson 4: Arrays and Lists ................................................................................................. 31
C# Basic – Lesson 5: Methods, Exception Treatments, Classes and Object-Oriented ........................... 40
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 3
Lesson 1: Installing Visual Studio and say “Hello World”! By Allan Carlos Claudino Villa
In this lesson, we are going to download our IDE, Visual Studio Community 2015, learn how to install
and configure it and write our first program that shows on the screen the sentence “Hello World”.
Before we get start, we need to know, what is an IDE?. IDE stands for Integrated Development
Environment, in the computer area. An IDE is a software suite where developers can write and test their
software. We will use Visual Studio Community 2015 as our IDE for these tutorial series.
Visual Studio is a powerful IDE from Microsoft. It not only has tools to create software since UI design,
coding, testing and debugging, but also websites, applications, and services. Our focus in this course is to
learn the language C#.
As I said, we will use C# as our programming language. ‘C-Sharp’ is an object-oriented language created
by Microsoft. Based on C++ and JAVA, C# offers the same power as the C++ with the ease of Visual Basic
programming. So, let’s get started!
DOWNLOADING AND INSTALLING VISUAL STUDIO COMMUNITY 2015
Click here to visit Visual Studio website and click on ‘Download Community Free’.
After download, execute it.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 4
Choose your installation location -> Select Default Installation -> Click Install.
After the installation, if it asks for RESTART, please do it; otherwise, click LAUNCH.
When you open Visual Studio Community for the first time, it asks for Sign In. We can do it later. Now
click on ‘Not now, maybe later’.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 5
Here you can you choose your color theme. I use Blue theme. You can change it later. After selecting
your theme, click on Start Visual Studio.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 6
Here is where you can change your color theme inside Visual Studio. Tools -> Options -> Environment –>
Color Theme
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 7
Congratulations. You have installed Visual Studio Community 2015. Let’s write our first code!
HELLO WORLD
To write our programs, we will use a simple console application. Follow the steps below to start writing
our first program and run it in a console application.
File -> New -> Project.
Installed -> Templates -> Visual C# -> Windows –> Console Application.
Name: HelloWorld;
Location: Choose a location to save your project;
Solution name: HelloWorld. Click OK.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 8
This is how it looks after you have clicked OK.
Write or copy and paste the code below into Visual Studio code area. In the following tutorials, we are
going to understand every single line of the program.
1
2
using System;
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 9
3
4
5
6
7
8
9
10
1
12
13
14
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine("Welcome to Learning C# with ZENVA!!");
Console.Read();
}
}
}
Let’s understand what we wrote:
Console.WriteLine(): print a text and jump to another line.
Console.Read(): wait for the user to press a key to end the program.
The using above everything is a type of statement used to refer to a namespace that can be present in
a dll in order to easily access classes that are within this namespace. In our case, we are using “System”.
Without it, instead of writing Console.Writeline, we should write System.Console.Writeline.
To save our application, click on Save Program or press Ctrl+ S.
To run the application, we simply click on Start or press F5. Let’s run our application.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 10
Did you see how easy is that?
This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!
Thank you!
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 11
Lesson 2: Operators, Variables and Data Types. By Allan Carlos Claudino Villa
Tutorial Source Code
All of the source code for this tutorial can be downloaded here.
In this lesson, we are going to see two most used types of operators: arithmetic and logical/relational. In
addition, we are going to learn about some data types in C# and what is and how to declare a variable.
Last but not least, we are going to work with the data type string.
OPERATORS
Let’s see how Logical/Relational operators work, considering A = 5 and B = 10
Now, considering A = 2 and B = 5
Hello and welcome to the Lesson 2 – Operator, Variables and Data Types on our tutorial series Learning
C# with Zenva.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 12
Tutorial Source Code
All of the source code for this tutorial can be downloaded here.
In this lesson, we are going to see two most used types of operators: arithmetic and logical/relational. In
addition, we are going to learn about some data types in C# and what is and how to declare a variable.
Last but not least, we are going to work with the data type string.
OPERATORS
Let’s see how Logical/Relational operators work, considering
A + B = 7;
A – B = -3;
A * B = 10;
B / A = 2;
B % A = 1;
++A = 3;
– –B = 4;
DATA TYPES
A data type is a group of data with predefined characteristics in its value. Some example of these values
are found on the table below:
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 13
Source: https://androidkennel.org/zero-day-java-guide-1-installation-and-hello-variables/
VARIABLES
A variable is a name given to a storage area that our programs can manipulate. It can be local or
attribute of a class. To declare a variable, we need to specify its type and name (<data_type>
<variable_name>). In addition, there are some access modifiers we are going to learn in this lesson that
are not so important now.
Each programming language has its own rules for naming variables. Here we have rules for giving a
name to a variable in C#.
Variable names must begin with a letter of the alphabet;
Variables may contain letters and the digits 0 to 9. Not allowed: space or special characters, for instance
? ! @ # + – % ^ & *() [] {}.’;:”/ and \.
Variable names cannot be a Keywords belonging to C#. Example: continue, checked, public, return, etc;
C# is case sensitive, it means that var1 != Var1. (!= means different).
It is time to write some code using what we have learned so far. We are going to write examples using
the Arithmetic Operator. Logical and Relational operators will be used as examples in lesson 4.
Open Visual Studio Community 2015, go to File -> New -> Project.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 14
Installed -> Templates -> Visual C# -> Windows –> Console Application.
Name: Operators;
Location: Choose a location to save your project;
Solution name: Operators. Click OK.
Write or copy and paste the code below into Visual Studio code area.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
namespace Operators
{
public class Program
{
static void Main(string[] args)
{
int a;
int b;
a = 5;
b = 10;
Console.WriteLine("A + B = "+ (a + b));
Console.WriteLine("A - B = "+ (a - b));
Console.WriteLine("A * B = "+ (a * b));
Console.WriteLine("B / A = "+ (b / a));
Console.WriteLine("B % A = "+ (b % a));
Console.WriteLine("Increase a = "+ ++a);
Console.WriteLine("Decrease b = "+ --b);
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 15
22
23
24
25
Console.Read();
}
}
}
Understanding new code:
int a; int b; = declaring a variable of type Integer.
a = 5; b = 10; = initializing variables.
Console.Writeln(“A + B”+ (a+b)); = after the string “A+B” we add the “+” (plus) to concatenate to a
variable. Also, we wrote (a+b) inside a parentheses to indicate that this action performs first, and then
we concatenate with the string. If we had writing (“A + B ”+ a+b), the results would be “ A + B = 510 ”.
The program would concatenate a and b, not sum them.
Console.WriteLine(“Increase a = ” + ++a); = increasing variable “a”.
Console.WriteLine(“Decrease b = ” + –b); = decreasing variable “b”.
To save our application, click on Save Program or press Ctrl+ S.
To run the application we simple click on Start or press F5. Let’s run our application: F5
STRINGS
The data type string is so powerful that has its own class and also has some methods. In Lesson 5 we are
going to learn more about classes and how to work with methods. We will have a preview of these
contents here, but it is not our focus now. So, let’s begin!
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 16
String Properties
As I mentioned above, the class string holds methods and properties. When we declare a string, we can
have access to its properties by pressing dot and our IDE will show us what methods and properties are
accessible to use.
In the example below, we have chosen to use the property Length. This property gets the number of
characters in the current string, including spaces.
Let’s write some code. Start a new project, name it Strings and write or copy and paste the code below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
namespace Strings
{
class Program
{
static void Main(string[] args)
{
string str1 = "Learning C# with Zenva!";
Console.WriteLine("The length of str1 is:" + str1.Length);
Console.Read();
}
}
}
In this example, I declared a str1 type string and initialized its value with a string, because it will only
accept strings. Press F5 to run our application.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 17
Note that to access the properties from the variable, in this case, string type, after the name of the
variable, we put a dot(.) to see its properties and methods. In our example, we access the property
“Length”.
String methods
Below we have a few methods that we can use with the String class. Some of these methods, we are
going to write a the code for them using the structure conditional ‘IF’. This structure we are going to
learn in Lesson 3 which wraps the flow control in C#.
Compare: This method compares two strings if they are equals or not and return 0 if it is true, else 1 if it
is false.
Concat: This method concatenate two strings and return as resulst both strings together.
Contains: This method verify if there is a(some) word(s) in the current string I passed.
Replace: This method substitute a string to another.
ToUpper: This method gets the string I am calling this method from and return the same string but now
in uppercase.
ToLower: This method gets the string I am calling this method from and return the same string but now
in lowercase.
Trim: Removes the space of a string.
The table below show us some examples using these methods we learnt above.
Let’s consider we have two variables type string: str1 = “Learning C# with” and str2 = “ Zenva.”;
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 18
Every method has a return. In italic is what the method returns and this returns will be explained in
Lesson 5 – Methods, Exception Treatments, Classes and Object-Oriented
These are just a few examples of string methods. When writing code with the IDE Visual Studio, it shows
us tips and how some methods, for example, work. Get used to started learning with Visual Studio too.
This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!
Thank you!
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 19
C# Basic – Lesson 3: Flow Control in C#
By Allan Carlos Claudino Villa
Tutorial Source Code
All of the source code for this tutorial can be downloaded here.
Sometimes, a program needs to repeat a process until some condition is met. We call that “loop”. In
this lesson, we will see how to work with some structures as for instance, if statement, switch
statements, while, do while, for and foreach. Let’s begin.
IF STATEMENT
The instruction IF has the following syntax:
1
2
3
4
if(expression)
{
statement;
}
The “if” statement determines which way the program will continue. With the “if” statement, the
program has to decide if it will execute some code or not.
First example: Let’s write a code using the method “Compare” from the String class we learned in the
last lesson.
Considering str1 = “Learning C# with” and str2 = “Zenva.”;
Start a new project, name it FlowControlIfExample and write or copy and paste the code below.
1
2
3
4
5
6
7
using System;
namespace FlowControlIfExample
{
class Program
{
static void Main(string[] args)
{
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 20
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const string str1 = "Learning C# with ", str2 = "Zenva";
if(string.Compare(str1, str2) == 0)
{
Console.WriteLine("The two strings are equal!");
}
else
{
Console.WriteLine("The two strings are different");
}
Console.Read();
}
}
}
Understanding new code:
const string str1 = “Learning C# with”, str2 = “Zenva.”; Here I am declaring two constants, type string
and initializing its value. The word const before everything means that this constant will not be
modified. The two constants are separable by the comma.
As we observe, the program has an If statement to decide which way to go. In our example, we are
comparing two strings if they are equals. If the result is 0 or (true), the program executes the first
statement, else (meaning not true or 1) the program executes the second statement.
Running our program we have that the two strings are not equal.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 21
We can use a ternary operator (?:) too (if-then-else constructs).
1
2
3
4
int n1 = 5, n2 = 1;
string result = n1 > n2 ? "N1 is greater" : "N2 is greater";
//result: N1 is greater
Second example: using the methods “Contains” and “Replace”
Considering str1 = “Alan bought a Ferrari”;
1
2
3
4
5
6
7
8
9
10
using System;
namespace FlowControlIfExample
{
class Program
{
static void Main(string[] args)
{
// const string str1 = "Learning C# with ", str2 = "Zenva";
/* if(string.Compare(str1, str2) == 0)
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 22
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
Console.WriteLine("The two strings are equal!");
}
else
{
Console.WriteLine("The two strings are different");
} */
const string str1 = "Alan bought a Ferrari.";
//Verifying if the condition is NOT TRUE (!)
if (!str1.Contains("bought"))
{
Console.WriteLine("The str1 does not contain the word bought.");
}
else if (str1.Contains("Ferrari.")) //if the condition is TRUE
{
Console.WriteLine("What word do you want instead of Ferrari? ");
string str2 = Console.ReadLine(); //gets the string from the user
string str3 = str1.Replace("Ferrari", str2); //declaring str3 to receive the str1 content replaced
Console.WriteLine(str3); //showing the new sentence.
}
Console.Read();
}
}
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 23
38 }
To comment the code we can use “//” in front of the line or /* */ for a block. When we have
commented code, our application will not execute that line or block.
So in this code, we verify, if the first condition is NOT TRUE, (remember the operator “!”), we show a
message that the word we chose to check in contains method does not exist in the specified sentence. If
the word exists, then we go and check if exists the word “Ferrari”. If exists we ask for the user what
word he wants instead of Ferrari. We read what the user type and store in the variable str2 that we just
created.
Using the method replace, we pass the str1 + the new word using the replace method to the str3 and
show it in the console application.
SWITCH STATEMENT
This statement is another way to simulate the use of several if statements. When the condition is met,
we use the word “break” to interrupt the program of keep looking for other condition inside this
statement. All early types (int, string, double, etc.) can be used with the instruction “switch.”
The instruction SWITCH has the following syntax:
1
2
switch(expression)
{
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 24
3
4
5
6
7
case constant-expression:
statement(s);
break;
default: default expression;
}
Example: The program asks the user to type a value between 1 and 7 which determines the day of the
week.
For this example, let’s create another project and give it a name FlowControlExamples.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
namespace FlowControlExamples
{
class Program
{
static void Main(string[] args)
{
Console.Write("Type a number 1 - 7 to see the day of the week corresponding to this number: ");
//Converting string to Int32.
int numberDayOfWeek = Convert.ToInt32(Console.ReadLine());
switch (numberDayOfWeek) //Checking the number the user typed.
{
case 1:
Console.WriteLine("The day number "+ numberDayOfWeek +" is Sunday!");
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 25
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
break;
case 2:
Console.WriteLine("The day number " + numberDayOfWeek + " is Monday!");
break;
case 3:
Console.WriteLine("The day number " + numberDayOfWeek + " is Tuesday!");
break;
case 4:
Console.WriteLine("The day number " + numberDayOfWeek + " is Wednesday!");
break;
case 5:
Console.WriteLine("The day number " + numberDayOfWeek + " is Thursday!");
break;
case 6:
Console.WriteLine("The day number " + numberDayOfWeek + " is Friday!");
break;
case 7:
Console.WriteLine("The day number " + numberDayOfWeek + " is Saturday!");
break;
default: Console.WriteLine("This number is invalid.");
break;
}
Console.Read();
}
}
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 26
45 }
Understanding new code:
As everything the user writes is a string, a number written in the console application is a
string that needs to be converted to int type when the user writes numbers.
The difference between int16, int32, and int64 is their length.
Int16 — (-32,768 to +32,767)
Int32 — (-2,147,483,648 to +2,147,483,647)
Int64 — (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
Running our application:
Imagine that the user is a nice guy and writes only numbers. But, what if the user had written text
instead of numbers? An exception will be triggered because we are trying to convert letters to an int
type. In this case, we had a FormatException.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 27
Handling exceptions will be discussed in Lesson 06.
While and Do/While statements
While: used to repeat a block of code until a condition is true. The condition to execute the loop must
be a boolean value.
The instruction WHILE has the following syntax:
1
2
3
4
While (expression)
{
statements;
}
Do/While: works as same as the while, but using this statement we have our code executed at least
once.
1
2
using System;
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 28
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace FlowControlExamples
{
class Program
{
static void Main(string[] args)
{
#region
int x = 0; //creating a variable int starting with 0 as value.
//Here the program shows us 0 as result
Console.WriteLine("The value of 'x' is: "+ x);
//the program shows x incrementing one by one until 10.
//++x means x = x + 1;
while (x < 10)
{
Console.WriteLine("The value of 'x' is: " + ++x);
}
Console.Read();
}
}
}
As you can see, there is a different word in the code: #region. My last code is all commented inside this
“region”.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 29
Running our application:
FOR / FOREACH
Also used for loops, but the difference is that here we already know how many times the condition will
repeat. We declare a counter variable, which is automatically increased or decreased in value during
each repetition of the loop.
The instruction FOR has the following syntax:
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 30
1
2
3
4
for (initialisation, expression, variable update)
{
statements;
}
1
2
3
4
foreach (element in collection)
{
statements;
}
With the for statement we specify the loop bounds (minimum or maximum) while with the foreach
statement we do not need to specify a boundary.
We will write some code using the command for and foreach in the next lesson!
This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!
Thank you!
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 31
Lesson 4: Arrays and Lists By Allan Carlos Claudino Villa
Tutorial Source Code
All of the source code for this tutorial can be downloaded here.
In this lesson, we will see what is an array and what is a list; the difference between them; how to
declare and use them together with the for statement we learnt in the last lesson.
ARRAYS
An Array is a data collection of the same type. A feature of the arrays is that they are static, that is, the
programmer cannot increase the amount of positions in runtime. So if we declare an array of int with 10
positions, these positions will remain until the end of the program for this array.
Arrays have the following syntax:
1 Data type[] arrayName;
Data Type: specify the type of elements in the array.
[ ] : specify the size of the array.
arrayName: specify the name of the array.
When we declare an array, it does not mean it is initialized in the memory because by now, we cannot
assign values to it.
Arrays, lists and objects, need to be initialized so we can assign them values. To initialized these structs,
we use the word new. For example:
1 int[] ages = new int[5]
Remember: An array start its index in position 0. It means, an array with 3 positions will have as index:
[0][1][2]. We can have access to the array content using the index. There are several ways to assign
value to an array. Let’s see them:
Using the index number:
1
2
string[] names = new string[5]
names[0] = "Zenva";
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 32
When we declare the array:
1
2
3
4
5
int[] numbers = new int[5] {10, 20, 30, 40, 50}
double[] salary = {150.0, 2400.0, 175.39, 788.68}
//In this case, the array salary has 4 positions.
We can also omit the size:
1
2
3
int[] score = new int[] {10, 20, 30, 40, 50}
//In this case, the array length is 5.
Note: ‘//’ is used to write comments in the code.
We can assign a value from an array, using the index, to a variable:
1
2
3
int[] numbers = new int[5] {10, 20, 30, 40, 50}
int n1 = numbers[3]; //Now n1 = 30.
Time to write some code! Let’s start a new Project and name it ArrayAndList. Write or copy and paste
the code below.
Array example:
1 using System;
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace ArrayAndList
{
class Program
{
static void Main(string[] args)
{
//String array with 3 elements
string[] names = new string[3];
names[0] = "Davis";
names[1] = "Matt";
names[2] = "Bob";
for(int i = 0; i < names.Length; i++)
{
Console.WriteLine("Position number "+ i +": "+ names[i]);
}
Console.Read();
}
}
}
In this example, we declared an array of type string with 3 positions and we wrote one name on each
position. Then we showed that content of the array using a flow control we learnt last lesson, “for”, to
go through each position of the array. Reading the command: “from i = 0 to names.length (in this case
length = 3), do something, then, increment the variable i.”
Running our application:
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 34
We can also use the structure for to fill our array with numbers, for instance:
1
2
3
4
5
6
7
int[] numbers = new int[3];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = i + 5;
Console.WriteLine("Our array numbers has in position [" + i + "] the value: " + numbers[i]);
}
LISTS
A List(T) has the same characteristics of an array. However, a List(T) can be increased dynamically. In a
List(T), we do not establish its length. As we need more values to be put into a list, we simply write the
method ‘Add’ and we add a new value.
A List(T) has the following syntax:
1 List<data type> listName;
Also to initialize the list we use the word ‘new’.
1 listName = new List<data type>();
Both arrays and lists are very easy to work. Also, they are simple and powerful.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 35
List example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Collections.Generic;
namespace ArrayAndList
{
class Program
{
static void Main(string[] args)
{
#region
//Declaring a list "int".
List<int> list = new List<int>();
//Populating the list with 10 elements
for(int i = 0; i <= 10; i++)
{
list.Add(i*9);
}
int x = 0;
//foreach element in the list do:
foreach(int element in list)
{
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 36
26
27
28
29
30
31
32
33
Console.WriteLine("9 * " + x + " = " + element);
x++;
}
Console.Read();
}
}
}
In this example, we did the multiplication table 9. It was declared a list of type int and we add some
numbers using the repeat loop for. Then we showed its content by using the foreach. Also, we need to
declare on the top of the code, the using System.Collections.Generic to be able to use List(T).
Running our application:
We can also add items provided by an array in a list. With an array to check its size, we use the method
length. With a List(T), we use the method Count.
1
2
3
4
5
6
List<double> orders = new List<double>(new double[] { 19.99, 6.48, 25.0 });
for (int i = 0; i < orders.Count ; i++)
{
Console.WriteLine("Order number " + i + " : $ " + orders[i]);
}
Count: We can assign the size of a list to a variable by writing:
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 37
1
2
3
4
5
int ordersQuantity = orders.Count;
Console.WriteLine(ordersQuantity);
//Result: 3
Clear: To remove all the elements from a list we use the function Clear().
1
2
3
4
5
orders.Clear();
Console.WriteLine(orders.Count);
//Result: 0
IndexOf: Give us the element index of a value in the List(T). When the method IndexOf does not find the
value, it returns as value -1;
1
2
3
4
int index = orders.IndexOf(25.0);
Console.WriteLine(index);
//Result: 2
Reverse: Invert the order of the elements in the list.
1
2
List<string> cars = new List<string>(new string[] { "Ferrari", "Lamborghini", "Range Rover" });
cars.Reverse();
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 38
3
4
5
6
7
8
9
10
11
12
foreach (var car in cars)
{
Console.WriteLine(car);
}
//Result:
//Range Rover
//Lamborghini
//Ferrari
Distinct: Remove duplicates elements in the list. This method belongs to System.Linq, so we need to add
this using System.Linq in our application.
1
2
3
4
5
6
7
8
9
10
11
12
13
List<int> oldList = new List<int>(new int[] { 1, 2, 2, 3, 4, 4, 5 });
//Get distinct elements and convert into a list again.
List<int> newList = oldList.Distinct().ToList();
foreach (var item in newList)
{
Console.WriteLine(item);
}
//Result
//1
//2
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 39
14
15
16
//3
//4
//5
This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!
Thank you!
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 40
Lesson 5: Methods, Exception Treatments, Classes and Object-Oriented By Allan Carlos Claudino Villa
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 organize 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:
1
2
3
4
<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.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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);
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 42
28
29
30
31
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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 43
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{
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");
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 44
43
44
45
46
47
48
}
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:
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 45
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:
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 46
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.
1
2
3
4
5
6
7
8
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.
1 try
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
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
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 48
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:
1
2
3
4
5
6
7
8
9
10
11
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!!
1
2
3
namespace ClassesAndObjects
{
public class Person
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 49
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
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.
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 50
Let’s set some values and show these values in our application.
1
2
3
4
5
6
7
8
9
10
11
using System;
namespace ClassesAndObjects
{
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public int age { get; set; }
}
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 51
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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:
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 52
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.
1 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.
1 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
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!";
}
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 53
14 }
Now let’s receive the user age and check if the user is of legal age by calling the method
AgeOfMajority();
1
2
3
4
5
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!
Zenva Academy – Online courses on game, web and mobile app development
©2016 Zenva Pty Ltd all rights reserved
Page 54