0% found this document useful (0 votes)
17 views

CSharp Programming For Human Beings

The document provides an introduction to C# programming for human beings. It discusses installing Visual Studio and creating a "Hello World" program in C#. The summary discusses operators, variables, data types, and strings in C# programming.

Uploaded by

fablegamestudio
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

CSharp Programming For Human Beings

The document provides an introduction to C# programming for human beings. It discusses installing Visual Studio and creating a "Hello World" program in C#. The summary discusses operators, variables, data types, and strings in C# programming.

Uploaded by

fablegamestudio
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

C# Programming for Human Beings

By Allan Carlos Claudino Villa


Professional C# Developer

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to
master applying your C# skills to Unity!

© Zenva Pty Ltd 2016. All rights reserved


Before diving into this eBook, why not check out some
resources that will supercharge your coding skills:

Unlimited access to EVERY course on our Courses that will quickly get you coding
platform! Get new courses each month, with the world's most popular languages!
help from expert mentors, and guided Discover Python, web development, game
learning paths on popular topics. development, VR, AR, & more.

No experience is required to take this Learn how to build games with C# and
project-based course, which covers Unity! You'll master popular genres
variables, functions, conditionals, loops, including RPGs, idle games, Platformers,
and object-oriented programming. and FPS games.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to
master applying your C# skills to Unity!

© Zenva Pty Ltd 2016. All rights reserved


Table of Contents
C# Basic – Lesson 1: Installing Visual Studio and say “Hello World”! ....................................................4
C# Basic – Lesson 2: Operators, Variables and Data Types. ................................................................ 12
C# Basic – Lesson 3: Flow Control in C# ............................................................................................. 20
C# Basic – Lesson 4: Arrays and Lists ................................................................................................. 33
C# Basic – Lesson 5: Methods, Exception Treatments, Classes and Object-Oriented ........................... 42

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 3 © Zenva Pty Ltd 2016. All rights reserved


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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 4 © Zenva Pty Ltd 2016. All rights reserved


Choose your installation location -> Select Default Installation -> Click Install.

After the installation, if it asks for RESTART, please do it; otherwise, click LAUNCH.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 5 © Zenva Pty Ltd 2016. All rights reserved


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’.

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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 6 © Zenva Pty Ltd 2016. All rights reserved


Here is where you can change your color theme inside Visual Studio. Tools -> Options -> Environment –>
Color Theme

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 7 © Zenva Pty Ltd 2016. All rights reserved


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;

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 8 © Zenva Pty Ltd 2016. All rights reserved


Solution name: HelloWorld. Click OK.

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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 9 © Zenva Pty Ltd 2016. All rights reserved


1 using System;
2
3 namespace HelloWorld
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 Console.WriteLine("Hello World!");
10 Console.WriteLine("Welcome to Learning C# with ZENVA!!");
1 Console.Read();
12 }
13 }
14 }

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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 10 © Zenva Pty Ltd 2016. All rights reserved


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!

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 11 © Zenva Pty Ltd 2016. All rights reserved


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

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 12 © Zenva Pty Ltd 2016. All rights reserved


Hello and welcome to the Lesson 2 – Operator, Variables and Data Types on our tutorial series Learning
C# with Zenva.

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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 13 © Zenva Pty Ltd 2016. All rights reserved


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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 14 © Zenva Pty Ltd 2016. All rights reserved


Open Visual Studio Community 2015, go to File -> New -> Project.

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 using System;
2
3 namespace Operators
4 {
5 public class Program
6 {
7 static void Main(string[] args)
8 {
9 int a;
10 int b;
11
12 a = 5;
13 b = 10;
14
15 Console.WriteLine("A + B = "+ (a + b));
16 Console.WriteLine("A - B = "+ (a - b));
17 Console.WriteLine("A * B = "+ (a * b));
18 Console.WriteLine("B / A = "+ (b / a));
19 Console.WriteLine("B % A = "+ (b % a));

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 15 © Zenva Pty Ltd 2016. All rights reserved


20 Console.WriteLine("Increase a = "+ ++a);
21 Console.WriteLine("Decrease b = "+ --b);
22 Console.Read();
23 }
24 }
25 }

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

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 16 © Zenva Pty Ltd 2016. All rights reserved


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!

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 using System;
2
3 namespace Strings
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 string str1 = "Learning C# with Zenva!";
10
11 Console.WriteLine("The length of str1 is:" + str1.Length);
12 Console.Read();
13 }
14 }
15 }

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 17 © Zenva Pty Ltd 2016. All rights reserved


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.

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.”;

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 18 © Zenva Pty Ltd 2016. All rights reserved


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!

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 19 © Zenva Pty Ltd 2016. All rights reserved


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 if(expression)
2 {
3 statement;
4 }

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 using System;
2 namespace FlowControlIfExample
3 {
4 class Program
5 {
6 static void Main(string[] args)

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 20 © Zenva Pty Ltd 2016. All rights reserved


7 {
8 const string str1 = "Learning C# with ", str2 = "Zenva";
9
10 if(string.Compare(str1, str2) == 0)
11 {
12 Console.WriteLine("The two strings are equal!");
13 }
14 else
15 {
16 Console.WriteLine("The two strings are different");
17 }
18
19 Console.Read();
20 }
21 }
22 }

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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 21 © Zenva Pty Ltd 2016. All rights reserved


We can use a ternary operator (?:) too (if-then-else constructs).

1 int n1 = 5, n2 = 1;
2 string result = n1 > n2 ? "N1 is greater" : "N2 is greater";
3
4 //result: N1 is greater

Second example: using the methods “Contains” and “Replace”

Considering str1 = “Alan bought a Ferrari”;

1 using System;
2 namespace FlowControlIfExample
3 {
4 class Program
5 {
6 static void Main(string[] args)
7 {
8 // const string str1 = "Learning C# with ", str2 = "Zenva";

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 22 © Zenva Pty Ltd 2016. All rights reserved


9
10 /* if(string.Compare(str1, str2) == 0)
11 {
12 Console.WriteLine("The two strings are equal!");
13 }
14 else
15 {
16 Console.WriteLine("The two strings are different");
17 } */
18
19 const string str1 = "Alan bought a Ferrari.";
20
21 //Verifying if the condition is NOT TRUE (!)
22 if (!str1.Contains("bought"))
23 {
24 Console.WriteLine("The str1 does not contain the word bo
25 }
26 else if (str1.Contains("Ferrari.")) //if the condition is TR
27 {
28 Console.WriteLine("What word do you want instead of Ferr
29 string str2 = Console.ReadLine(); //gets the string from
30
31 string str3 = str1.Replace("Ferrari", str2); //declaring
replaced
32
33
Console.WriteLine(str3); //showing the new sentence.
34

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 23 © Zenva Pty Ltd 2016. All rights reserved


35 }
36 Console.Read();
37 }
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 book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 24 © Zenva Pty Ltd 2016. All rights reserved


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 switch(expression)
2 {
3 case constant-expression:
4 statement(s);
5 break;
6 default: default expression;
7 }

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 using System;
2
3 namespace FlowControlExamples
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 Console.Write("Type a number 1 - 7 to see the day of the wee
");
10

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 25 © Zenva Pty Ltd 2016. All rights reserved


11
12 //Converting string to Int32.
13 int numberDayOfWeek = Convert.ToInt32(Console.ReadLine());
14
15 switch (numberDayOfWeek) //Checking the number the user type
16 {
17 case 1:
18 Console.WriteLine("The day number "+ numberDayOfWeek
19 break;
20 case 2:
21 Console.WriteLine("The day number " + numberDayOfWee
22 break;
23 case 3:
24 Console.WriteLine("The day number " + numberDayOfWee
25 break;
26 case 4:
27 Console.WriteLine("The day number " + numberDayOfWee
28 break;
29 case 5:
30 Console.WriteLine("The day number " + numberDayOfWee
31 break;
32 case 6:
33 Console.WriteLine("The day number " + numberDayOfWee
34 break;
35 case 7:
36 Console.WriteLine("The day number " + numberDayOfWee

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 26 © Zenva Pty Ltd 2016. All rights reserved


37 break;
38
39 default: Console.WriteLine("This number is invalid.");
40 break;
41 }
42
43 Console.Read();
44 }
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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 27 © Zenva Pty Ltd 2016. All rights reserved


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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 28 © Zenva Pty Ltd 2016. All rights reserved


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 While (expression)
2 {
3 statements;
4 }
Do/While: works as same as the while, but using this statement we have our code executed at least
once.

1 using System;
2
3 namespace FlowControlExamples
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 #region
10
11 int x = 0; //creating a variable int starting with 0 as
value.
12
13
//Here the program shows us 0 as result
14

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 29 © Zenva Pty Ltd 2016. All rights reserved


15 Console.WriteLine("The value of 'x' is: "+ x);
16
17 //the program shows x incrementing one by one until 10.
18 //++x means x = x + 1;
19 while (x < 10)
20 {
21 Console.WriteLine("The value of 'x' is: " + ++x);
22 }
23
24 Console.Read();
25 }
26 }
}

As you can see, there is a different word in the code: #region. My last code is all commented inside this
“region”.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 30 © Zenva Pty Ltd 2016. All rights reserved


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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 31 © Zenva Pty Ltd 2016. All rights reserved


1 for (initialisation, expression, variable update)
2 {
3 statements;
4 }

1 foreach (element in collection)


2 {
3 statements;
4 }

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!

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 32 © Zenva Pty Ltd 2016. All rights reserved


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 string[] names = new string[5]

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 33 © Zenva Pty Ltd 2016. All rights reserved


2 names[0] = "Zenva";

When we declare the array:

1 int[] numbers = new int[5] {10, 20, 30, 40, 50}


2
3 double[] salary = {150.0, 2400.0, 175.39, 788.68}
4
5 //In this case, the array salary has 4 positions.

We can also omit the size:

1 int[] score = new int[] {10, 20, 30, 40, 50}


2
3 //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 int[] numbers = new int[5] {10, 20, 30, 40, 50}


2
3 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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 34 © Zenva Pty Ltd 2016. All rights reserved


1 using System;
2
3 namespace ArrayAndList
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 //String array with 3 elements
10 string[] names = new string[3];
11 names[0] = "Davis";
12 names[1] = "Matt";
13 names[2] = "Bob";
14
15 for(int i = 0; i < names.Length; i++)
16 {
17 Console.WriteLine("Position number "+ i +": "+
names[i]);
18
}
19
20
Console.Read();
21
}
22
}
23
}

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 35 © Zenva Pty Ltd 2016. All rights reserved


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:

We can also use the structure for to fill our array with numbers, for instance:

1 int[] numbers = new int[3];


2
3 for (int i = 0; i < numbers.Length; i++)
4 {
5 numbers[i] = i + 5;
6 Console.WriteLine("Our array numbers has in position [" + i + "] the
numbers[i]);
7
}

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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 36 © Zenva Pty Ltd 2016. All rights reserved


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.

List example:

1 using System;
2 using System.Collections.Generic;
3
4 namespace ArrayAndList
5 {
6 class Program
7 {
8 static void Main(string[] args)
9 {
10 #region
11
12 //Declaring a list "int".
13 List<int> list = new List<int>();
14
15 //Populating the list with 10 elements
16 for(int i = 0; i <= 10; i++)
17 {

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 37 © Zenva Pty Ltd 2016. All rights reserved


18 list.Add(i*9);
19 }
20
21 int x = 0;
22
23 //foreach element in the list do:
24 foreach(int element in list)
25 {
26 Console.WriteLine("9 * " + x + " = " + element);
27 x++;
28 }
29
30 Console.Read();
31 }
32 }
33 }
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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 38 © Zenva Pty Ltd 2016. All rights reserved


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 List<double> orders = new List<double>(new double[] { 19.99, 6.48, 25.0 }


2
3 for (int i = 0; i < orders.Count ; i++)
4 {
5 Console.WriteLine("Order number " + i + " : $ " +
orders[i]);
6
}
Count: We can assign the size of a list to a variable by writing:

1 int ordersQuantity = orders.Count;


2
3 Console.WriteLine(ordersQuantity);
4
5 //Result: 3

Clear: To remove all the elements from a list we use the function Clear().

1 orders.Clear();
2
3 Console.WriteLine(orders.Count);
4
5 //Result: 0

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 39 © Zenva Pty Ltd 2016. All rights reserved


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 int index = orders.IndexOf(25.0);


2 Console.WriteLine(index);
3
4 //Result: 2

Reverse: Invert the order of the elements in the list.

1 List<string> cars = new List<string>(new string[] { "Ferrari", "Lamborg


});
2
cars.Reverse();
3
4
foreach (var car in cars)
5
{
6
Console.WriteLine(car);
7
}
8
9
//Result:
10
//Range Rover
11
//Lamborghini
12
//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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 40 © Zenva Pty Ltd 2016. All rights reserved


1 List<int> oldList = new List<int>(new int[] { 1, 2, 2, 3, 4, 4, 5 });
2
3 //Get distinct elements and convert into a list again.
4 List<int> newList = oldList.Distinct().ToList();
5
6 foreach (var item in newList)
7 {
8 Console.WriteLine(item);
9 }
10
11 //Result
12 //1
13 //2
14 //3
15 //4
16 //5
This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!

Thank you!

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 41 © Zenva Pty Ltd 2016. All rights reserved


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 <access specifier> <Return type> <Method name> (Parameter List)


2 {
3 Method body
4 }

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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 42 © Zenva Pty Ltd 2016. All rights reserved


1 using System;
2
3 namespace MethodsAndException
4 {
5 public class Program
6 {
7 //method is static because I am calling it from the static met
8 public static void SumTwoNumbers(int number1, int number2)
9 {
10 Console.WriteLine(number1 + " + " + number2 + " = " + (num
number2));
11
}
12
13
14
public static void Main(string[] args)
15
{
16
int n1, n2;
17
18
Console.WriteLine("Give me two numbers and I give you thei
19
Console.Write("What is your first number: ");
20
n1 = Convert.ToInt32(Console.ReadLine());
21
Console.Write("What is your second number: ");
22
n2 = Convert.ToInt32(Console.ReadLine());
23
24
//calling the method.
25

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 43 © Zenva Pty Ltd 2016. All rights reserved


26 //SumTwoNumbers(n1, n2);
27
28
29 Console.Read();
30 }
31 }
}

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 using System;
2
3 namespace MethodsAndException
4 {
5 public class Program
6 {
7 ////method is static because I am calling it from the static me
8 //public static void SumTwoNumbers(int number1, int number2)
9 //{
10 // Console.WriteLine(number1 + " + " + number2 + " = " + (nu
11 //}

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 44 © Zenva Pty Ltd 2016. All rights reserved


12
13
14 //method return is a bool value (true or false)
15 public static bool WhoIsGreater(int A, int B)
16 {
17 if (A > B)
18 return true;
19 else
20 return false;
21 }
22
23 public static void Main(string[] args)
24 {
25 //int n1, n2;
26
27 //Console.WriteLine("Give me two numbers and I give you the
28 //Console.Write("What is your first number: ");
29 //n1 = Convert.ToInt32(Console.ReadLine());
30 //Console.Write("What is your second number: ");
31 //n2 = Convert.ToInt32(Console.ReadLine());
32
33 //calling the method.
34 //SumTwoNumbers(n1, n2);
35
36 if (WhoIsGreater(10, 5)) //if is true than A > B. Here you
testing.
37

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 45 © Zenva Pty Ltd 2016. All rights reserved


38 {
39 Console.WriteLine("A is greater than B");
40 }
41 else
42 {
43 Console.WriteLine("A is greater than B");
44 }
45
46 Console.Read();
47 }
48 }
}

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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 46 © Zenva Pty Ltd 2016. All rights reserved


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:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 47 © Zenva Pty Ltd 2016. All rights reserved


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 try
2 {
3
4 }
5 catch (Exception)
6 {
7 throw;
8 }

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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 48 © Zenva Pty Ltd 2016. All rights reserved


1 try
2 {
3 Console.WriteLine("Give me two numbers and I give you their sum!");
4 Console.Write("What is your first number: ");
5 n1 = Convert.ToInt32(Console.ReadLine());
6 Console.Write("What is your second number: ");
7 n2 = Convert.ToInt32(Console.ReadLine());
8
9 //calling the method.
10 SumTwoNumbers(n1, n2);
11 }
12 catch (Exception)
13 {
14 Console.WriteLine("This is not a number!");
15 }

Now, our exception is treated!

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 49 © Zenva Pty Ltd 2016. All rights reserved


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:

1 namespace ClassesAndObjects
2 {
3 public class Program
4 {
5 public static void Main(string[] args)

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 50 © Zenva Pty Ltd 2016. All rights reserved


6 {
7 string firstname, lastName;
8 int age;
9 }
10 }
11 }

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 namespace ClassesAndObjects
2 {
3 public class Person
4 {
5 public string firstName { get; set; }
6 public string lastName { get; set; }
7 public int age { get; set; }
8 }
9
10 public class Program
11 {
12 public static void Main(string[] args)
13 {
14
15 }
16 }

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 51 © Zenva Pty Ltd 2016. All rights reserved


17 }

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.

1 using System;

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 52 © Zenva Pty Ltd 2016. All rights reserved


2
3 namespace ClassesAndObjects
4 {
5 public class Person
6 {
7 public string firstName { get; set; }
8 public string lastName { get; set; }
9 public int age { get; set; }
10 }
11
12 public class Program
13 {
14 public static void Main(string[] args)
15 {
16 //declaring a variable type Person (class)
17 Person p = new Person();
18 p.firstName = "Alex";
19 p.lastName = "Wilson";
20 p.age = 37;
21
22 Console.WriteLine("Hi, my name is "+ p.firstName +" "+ p.l
old.");
23
Console.Read();
24
}
25
}
26
}

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 53 © Zenva Pty Ltd 2016. All rights reserved


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.

1 Console.WriteLine("Hi, my name is {0} {1} {2} years old.", p.firstName,


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.

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 54 © Zenva Pty Ltd 2016. All rights reserved


1 public class Person
2 {
3 public string firstName { get; set; }
4 public string lastName { get; set; }
5 public int age { get; set; }
6
7 public string AgeOfMajority(int age)
8 {
9 if (age >= 18)
10 return "You are of legal age!";
11 else
12 return "You are not of legal age!";
13 }
14 }

Now let’s receive the user age and check if the user is of legal age by calling the method
AgeOfMajority();

1 Person p2 = new Person();


2 Console.Write("How old are you? ");
3 int myAge = Convert.ToInt32(Console.ReadLine());
4
5 Console.WriteLine(p2.AgeOfMajority(myAge));

Running our program:

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 55 © Zenva Pty Ltd 2016. All rights reserved


This is our last tutorial about learning Basic C# . I hope you have enjoyed.

Thank you!

This book is brought to you by Zenva - Enroll in our Unity Game Development Mini-Degree to master
applying your C# skills to Unity!

Page 56 © Zenva Pty Ltd 2016. All rights reserved

You might also like