Strings and numbers are not the only types of values. In this lesson, we'll look at a type called boolean.
Boolean values are quite special because they can only be true
or false
.
var newGame = true; Console.WriteLine (newGame);
//Output Below
True
There! As strange as it sounds, computers depend heavily on booleans.
Most of the time, we get booleans from comparing values and variables with each other.
We can use two equals signs (==
) to check if two values are the same.
The saying is that you should never compare apples to oranges. We'll do it anyway.
Console.WriteLine ("Apples" == "Oranges");
//Output Below
False
There! This comparison gives us a boolean: False
.
Let's check if these two strings are the same.
Console.WriteLine ("Apples" == "Apples");
//Output Below
True
Of course they are, which is why this comparison gives us True
.
We can store the results of these comparisons in variables.
var result = "Apples" == "Oranges"; Console.WriteLine (result);
//Output Below
False
Nice! We can assign the comparison just like a value.
There's a big difference between =
and ==
. We use =
to store values and ==
to compare them.
var result = "Apples" == "Oranges"; Console.WriteLine (result);
//Output Below
False
Fantastic! The =
sign stores values and the ==
sign compares them.
We can also check if two strings are not the same.
var result = "Apples" != "Oranges"; Console.WriteLine (result);
//Output Below
True
There! This operator is called not equals.
What about these two strings? Are they not the same?
var result = "Apples" != "Apples"; Console.WriteLine (result);
//Output Below
False
"Apples"
and "Apples"
are the same, which is why !=
returns False
.
We can use ==
and !=
to compare pretty much any type, including numbers.
Console.WriteLine (1 == 10);
//Output Below
False
Nice! Because 1
and 10
aren't the same, this comparison returns False
.
Let's compare these two numbers.
var result = 10 == 10; Console.WriteLine (result);
//Output Below
True
Great! The two numbers are the same.
We can also check if two numbers are different.
var result = 1 != 10; Console.WriteLine (result);
//Output Below
True
Great work! The comparison returns True
because the two numbers aren't equal.
This time we need the !=
operator.
For numbers, however, we can also find out how they differ from each other.
The <
sign, for example, can tell us if the number on the left is less than the number on the right.
var result = 1 < 10; Console.WriteLine (result);
//Output Below
True
There! Because 1
is indeed less than 10
, the comparison returns true
.
Of course that means we can also check if one number is greater than another.
var result = 1 > 10; Console.WriteLine (result);
//Output Below
False
Nice! Of course 1
isn't greater than 10
.
There's no need to compare values all the time, though. We can also use variables.
var number = 1; var result = number == 10; Console.WriteLine (result);
//Output Below
False
Sweet! The result is False
because the value of number
is 1
, which isn't equal to 10
.
With that, we can already check if a password is correct.
var password = "Swordfish"; var loggedIn = password == "Swordfish"; Console.WriteLine (loggedIn);
//Output Below
True
Nice! This is basically how code checks passwords.
Booleans are great because they let the computer make decisions whether to run certain lines of code or skip them.
We use the word if
to execute a line of code only if a certain boolean is true
.
if (true) { Console.WriteLine ("Hi!"); }
//Output Below
Hi!
There! This is what we call an if statement.
Let's make sure that this code displays Hi!
in the console.
if (true) { Console.WriteLine ("Hi!"); }
//Output Below
Hi!
Yes! Because the condition is true
, the computer executes the line.
Did you notice the parentheses, ()
, around true
? If you remember, parentheses contain information the computer either uses or checks.
Let's put together a basic if statement that displays Hi!
.
if (true) { Console.WriteLine ("Hi!"); }
//Output Below
Hi!
Nice! At this point true
is always true
, which means the app will always display Hi!
.
To make practical sense, an if statement needs a boolean value that's only true
if a condition is fulfilled.
Let's make an if statement that checks if we choose the first level of a game.
var level = "Level 1"; if (level == "Level 1") { Console.WriteLine ("Starting level 1"); }
//Output Below
Starting level 1
There! If statements can be used to build game menus.
Conditions in if statements work with all the comparisons we've already explored.
var level = "Level 1"; if (level == "Level 1") { Console.WriteLine ("Starting Level 1"); }
//Output Below
Starting Level 1
What a beautiful if statement!
We use curly braces ({}
) to mark the beginning and the end of the lines we want to depend on the condition.
var level = "Level 1"; if (level == "Level 1") { Console.WriteLine ("Starting Level 1"); }
//Output Below
Starting Level 1
Great! The opening brace ({
) goes after the condition. The closing brace (}
) goes below the line we want to depend on the condition.
We can also build if statements that depend on numbers.
Let's check if we gathered enough points to win the game.
var score = 100; if (score == 100) { Console.WriteLine ("Game won!"); }
//Output Below
Game won!
Yes! If statements work with doubles and integers alike.
We can also use the <
sign to check if score
is less than 100
.
var score = 50; if (score < 100) { Console.WriteLine ("You need more points!"); }
//Output Below
You need more points!
Nice work! This code will print "You need more points!"
to the console anytime the score
is less than 100
.
And the same is true for the greater than operator, of course.
var score = 111; if (score > 100) { Console.WriteLine ("New high score!"); }
//Output Below
New high score!
Great! We can set up an if statement to check if we got a new high score.
Game menus can have a lot options, though. What if the menu showed another 50 locked levels, would we write an if statement for each?
Nope! Instead, we can use the word else
to execute a different set of lines if the previous condition is false
.
var level = "Level 2"; if (level == "Level 3") { Console.WriteLine ("Starting Level 3!"); } else { Console.WriteLine ("Level locked!"); }
//Output Below
Level locked!
Look! Because the two strings are different, the computer runs the line of code from the else statement.
Let's build an else statement from scratch.
var score = 111; if (score < 100) { Console.WriteLine ("Almost there!"); } else { Console.WriteLine ("You won!"); }
//Output Below
You won!
Fantastic! If score
isn't less than 100
, it must be 100
or more.
Else needs to be the last part of an if statement.
if ("Start" == "Start") { Console.WriteLine ("Starting"); } else { Console.WriteLine ("Quitting"); }
//Output Below
Starting
Yes, that's the order that makes sense!
There's more! We can use the words else if
to add other conditions.
var hour = 12; if (hour < 12) { Console.WriteLine ("Good morning"); } else if (hour < 17) { Console.WriteLine ("Good afternoon"); }
//Output Below
Good afternoon
Great! Now the computer displays Good afternoon
when hour
isn't less than 12
but is less than 17
.
let's build such an else if statement from scratch.
var score = 111; if (score < 100) { Console.WriteLine ("Almost there!"); } else if (score > 100) { Console.WriteLine ("Over 100!"); }
//Output Below
Over 100!
Sweet! Else if statements are almost exactly like if statements.
After an if statement, we can use as many else if statements as we want.
var hour = 12; if (hour < 12) { Console.WriteLine ("Good morning"); } else if (hour < 17) { Console.WriteLine ("Good afternoon"); } else if (hour < 21) { Console.WriteLine ("Good evening"); }
//Output Below
Good afternoon
Good! Do you, too, find it strange that we consider 12 PM to be in the afternoon?
If we use an else statement, it needs to be the last statement in the list. Let's add it without help.
var hour = 23; if (hour < 12) { Console.WriteLine ("Good morning"); } else if (hour < 17) { Console.WriteLine ("Good afternoon"); } else if (hour < 21) { Console.WriteLine ("Good evening"); } else { Console.WriteLine ("Good night"); }
//Output Below
Good night
Great work! That's how computers know what kind of greeting to display.
Often times, computers need to repeat the same tasks over and over again.
var number = 1; Console.WriteLine (number); number = number + 1; Console.WriteLine (number); number = number + 1; Console.WriteLine (number);
//Output Below
1 2 3
Imagine how tedious it would be to repeat these lines even a handful of times!
There's no need for us to repeat the same set of lines over and over again though. We can use loops to do that work for us.
With the word while
, we can execute a set of lines while a certain condition returns true
.
while (true) { }
Nice! Now this loop runs while true
is, well, true
.
Again, we use curly braces to mark the beginning and the end of the lines we want to repeat.
while (true) { }
Sweet! {
goes after the condition and }
at the very end.
Let's see what happens when we add a Console.WriteLine ()
instruction to the loop.
while (true) { Console.WriteLine ("Hi!"); }
//Output Below
Hi! Hi! Hi! ...
Holy cow! Because the condition is always true
, the loop never stops.
If the condition is always true
, the loop never stops. Let's change that.
var run = true; while (run == true) { Console.WriteLine ("Hi!"); run = false; }
//Output Below
Hi!
Sweet! But now the loop stops right after its first run.
We can use a counter variable to control the number of times the loop runs.
var number = 1; while (number < 3) { Console.WriteLine (number); number = number + 1; }
//Output Below
1 2
There! Now the loop runs as long as number
is less than 3
.
To make the loop run as long as number
is less than or equal to 3
, we can use the <=
signs.
var number = 1; while (number <= 3) { Console.WriteLine (number); number = number + 1; }
//Output Below
1 2 3
Nice! Now the loop still runs when number
increases to 3
.
Let's create a while loop that displays Hi!
exactly three times.
var number = 1; while (number <= 3) { Console.WriteLine ("Hi!"); number = number + 1; }
//Output Below
Hi! Hi! Hi!
Perfect! In the beginning, number
has the value 1
. In the loop's third execution, number
increases to 4
and the loop stops.
We can name counter variables however we want. Developers often call them i
.
var i = 1; while (i <= 3) { Console.WriteLine (i); i = i + 1; }
//Output Below
1 2 3
Nice! This time we called the counter variable i
.
We can also have the counter variable start at 3
and count down.
var i = 3; while (i >= 1) { Console.WriteLine (i); i = i - 1; }
//Output Below
3 2 1
Sweet! Now the loop runs as long as i
is greater than 1
.
To include 1
in the countdown, we can use the symbol for greater than or equal to.
var i = 3; while (i >= 1) { Console.WriteLine (i); i = i - 1; }
//Output Below
3 2 1
Nice! It's the combination of >
and =
.
We can also add 1
to counter variables with a shortcut. All we have to do is add ++
after i
and it will automatically add 1
.
var i = 1; i++; Console.WriteLine (i);
//Output Below
2
Great! By simply writing i++
, the i
variable has its value increased by 1
.
The ++
shortcut comes in handy when writing loops.
var i = 1; while (i <= 3) { Console.WriteLine (i); i++; }
//Output Below
1 2 3
Nice work! We used i++
to add a 1
to the counter variable to make sure that the while loop eventually stops.
There's another, more concise way of looping through elements. It's called the for loop and it always needs a counter variable.
for (var i = 1; i <= 3; i++) { Console.WriteLine (i); }
//Output Below
1 2 3
Yes! That's what we call a for loop.
A for loop has all of the parts a while loop has, only they're all on the same line of code and separated with a ;
.
for (var i = 1; i <= 3; i++) { Console.WriteLine (i); }
//Output Below
1 2 3
Great! We can clearly see the three parts essential to a for loop.
Again, i
is a counter variable. This time, however, we're creating it in the first line of the loop.
for (var i = 1; i <= 3; i++) { Console.WriteLine (i); }
//Output Below
1 2 3
Exactly! Creating a counter variable in a for loop is the same as creating a normal variable.
The second part of the for loop is the condition. Just like while, the for loop will execute as long as the condition is true.
for (var i = 1; i <= 3; i++) { Console.WriteLine (i); }
//Output Below
1 2 3
That's it! The loop executes while the counter variable is less than or equal to 3
.
Finally, we add 1 to the counter variable each time it loops.
for (var i = 1;i <= 3; i++) { Console.WriteLine (i); }
//Output Below
1 2 3
Exactly! It's the same way we added 1
in the while loop, only this time we are doing it inside the parentheses of the for loop.
Now let's try and add all parts of the for loop in the correct order.
for (var i = 1; i <= 3; i++) { Console.WriteLine (i); }
//Output Below
1 2 3
Great work! That's a lot of action in one line, no?
At this point, we can only use loops for counting and other calculations.
for (var i = 1; i <= 3; i++) { Console.WriteLine (i * i); }
//Output Below
1 4 9
Not that big of a deal, right?
Very soon, however, we'll use loops to go through collections of values, which is what tons of games use them for.
var scores = new int[] { 92, 81, 60 }; for (var i = 0; i < 3; i++) { Console.WriteLine (scores[i]); }
//Output Below
92 81 60
Exciting times are ahead of us!
A so-called array is a collection of values of the same type. Let's make an array to store a list of numbers.
int[] numbers;
Nice! We create an array using its type followed by brackets and a name.
Before we can use an array, however, we need to initialize it.
int[] numbers = new int[4];
Sweet! We use the word new
to create an array. The number in the brackets says that the array will be able to store 4 elements.
Now that we have an empty array, how might we add elements to it?
int[] ages = new int[4]; ages[0] = 24;
Good job! Arrays are zero-indexed, which means that the index of the first element in the array is 0
, not 1
.
Populating arrays isn't that complicated, right? Still, there's an even quicker way to get a populated array.
string[] names = { "Neo", "Morpheus", "Trinity" };
Nice! We declare names
as a string
-type array, put values within a set of braces and voilà: we have a populated array.
Back to ages
and strings! Wait, why should we care about strings at the moment?
Well, if we want to use the Console.WriteLine ()
method to display the elements of an array, we need to convert it to a string.
int[] ages = { 30, 21, 27, 24 }; var s = String.Join ("-", ages); Console.WriteLine (s);
//Output Below
30-21-27-24
Exactly! String.Join ()
takes a string
-type separator and an array and combines the elements into a single string, putting the separator in between.
Sometimes we might want to sort the elements of an array. Lucky for us, there's a built-in method that does just that.
int[] ages = { 30, 21, 27, 24 }; Array.Sort (ages); var s = String.Join ("-", ages); Console.WriteLine (s);
//Output Below
21-24-27-30
Great! We can use Array.Sort ()
to sort the array in ascending order.
What do you think we'll need to use to find the length of an array?
string[] places = { "Gotham", "Star City", "Metropolis" }; Console.WriteLine (places.Length);
//Output Below
3
Good job! We can use the array's Length
property to tell us the number of elements in the array.
Sometimes we want to get a specific value from an array. Let's try to get "Batman"
from the array!
string[] heroes = { "Superman", "Batman", "Wolverine" }; string hero = heroes[1]; Console.WriteLine (hero);
//Output Below
Batman
Awesome! We just need to put the index of the value we want in the brackets after the array's name.
What if we realize that we made a mistake and have to change an element in an array? Well, we can replace elements.
int[] heights = { 165, 170, 277, 185, 200 }; heights[2] = 177; var s = string.Join (", ", heights); Console.WriteLine (s);
//Output Below
165, 170, 177, 185, 200
Great! We can replace an element by assigning a different value to it. That's pretty similar to changing the value of a regular variable, right?
We've been playing around with strings for some time. Let's take a moment to dig a little deeper, shall we?
string place = "New York"; Console.WriteLine (place);
//Output Below
New York
Awesome! We've been creating string
-type variables with string literals, a sequence of characters in quotation marks.
Let's look at a different way of creating strings, shall we? If we have a bunch of characters lying around, we can use the string class constructor.
char[] chars = { 'a', 'b', 'c' }; string word = new String (chars); Console.WriteLine (word);
//Output Below
abc
Nice! We've discovered a new type: char
. We write char
-type values in single quotation marks and use them for single characters.
In the past, we've used the +
operator to join or concatenate strings. But there's also a built-in method that can achieve the same results.
string str1 = "Hello "; string str2 = "Bill!"; string str3 = String.Concat(str1, str2); Console.WriteLine (str3);
//Output Below
Hello Bill!
Nice job! String.Concat ()
takes two or more string
-type values as arguments and returns them as a single string.
We can access characters in a string just like we access elements of an array: with an index.
string hero = "Chuck Norris"; Console.WriteLine (hero[4]);
//Output Below
k
Awesome work! Just like arrays, string
variables are zero-indexed.
Given the similarities we've discovered between string
-type values and arrays, it won't be hard to guess how we find the length of a string.
string name = "Bruce"; int length = name.Length; Console.WriteLine (length);
//Output Below
5
Awesome! We can use the Length
property to find the length of a string
-type value.
We all know the struggle of trawling pages of words to find the line of info we need. Well C# has the Contains()
method which saves the hassle!
string s1 = "C# is such a great language"; string s2 = "C#"; bool b = s1.Contains (s2); Console.WriteLine (b);
//Output Below
True
Awesome work! We put the string we're looking for in the parentheses of Contains ()
. It will return a bool
-type value that we can store in a variable.
We can also find the index of a certain character or string in a string.
string s1 = "C# is such an awesome language"; int index = s1.IndexOf ("awesome"); Console.WriteLine (index);
//Output Below
14
Right on! We call IndexOf ()
from the original string and pass it the char
or string
-type value we're looking for.
Sometimes we have or want to remove a part of a string. There are two ways to do that and both use the Remove ()
method.
string s1 = "Superman is the best ... not!"; string s2 = s1.Remove (8); string s3 = s1.Remove (20); Console.WriteLine (s2); Console.WriteLine (s3);
//Output Below
Superman Superman is the best
See that? We pass it the index from which we want to start removing; Remove ()
gets rid of everything from that index to the end of the string.
The second way to use the Remove ()
method gives us a little more control over what we remove.
string s1 = "Aquaman is not better than Superman!"; string s2 = s1.Remove (11, 16); string s3 = s1.Remove (11, 4); Console.WriteLine (s2); Console.WriteLine (s3);
//Output Below
Aquaman is Superman! Aquaman is better than Superman!
If you say so! This time, we pass two values to Remove ()
. The first is the index to start from; the second is the number of characters we want to get rid of.
Maybe we need to use a comma to separate the two values?
Also, we can replace every occurrence of a character or string with another character or string.
var s1 = "I'm such a bool bat!"; var s2 = s1.Replace("b", "c"); Console.WriteLine (s2);
//Output Below
I'm such a cool cat!
Yes you are! We used the Replace ()
method to replace every occurrence of "b"
, the first argument, with "c"
, the second argument.
A list is similar to an array in that they're both collections. Lists, however, can dynamically change their capacity as we add and remove values.
List<int> ages = new List<int> ();
See that? In order to declare and initialize a list, we specify the type of the values we want it to store.
If we want to use Console.WriteLine()
to display the elements in a list, we have to make it a string. We've seen this not too long ago, haven't we?
List<double> times = new List<double> (); times.Add (4.20); times.Add (7.30); times.Add (9.35); string s = String.Join(", ", times); Console.WriteLine (s);
//Output Below
4.2, 7.3, 9.35
Nice! We can use String.Join ()
, passing in the separator between elements and also the list we are joining.
It's pretty self-explanatory but, in order to add values to a list, we can use the Add ()
method.
var names = new List<string> (); names.Add ("Peter"); names.Add ("Lois"); names.Add ("Meg");
As we can see, we can also use var
to create names
. Every time we add a value to the list, its capacity will automatically grow.
So, how can we access a particular item in the names
list?
var names = new List<string> (); names.Add ("Peter"); names.Add ("Lois"); names.Add ("Meg"); Console.WriteLine (names[0]); Console.WriteLine (names[2]);
//Output Below
Peter Meg
Sweet! Just like we access items in an array, we write their zero-based index number in brackets after the list's name.
If the number of elements in a list is constantly changing, we might want to check how many elements there are every now and then, right?
var ages = new List<int> (); ages.Add (35); ages.Add (28); ages.Add (32); Console.WriteLine (ages.Count);
//Output Below
3
Well done! We use the Count
property to check how many variables there are in the list.
What if, rather than adding elements to the end of the list, we want to insert it at a specific position?
var days = new List<string> (); days.Add ("Monday"); days.Add ("Wednesday"); days.Insert(1, "Tuesday"); var s = String.Join (", ", days); Console.WriteLine (s);
//Output Below
Monday, Tuesday, Wednesday
Perfect! Just like the Insert ()
method we've seen in the strings chapter, this method has two parameters: the index to insert at and the value to insert.
What if we want to sort the elements of a list? It was pretty easy with arrays, so why don't we try it with lists?
var numbers = new List<int> (); numbers.Add (6); numbers.Add (2); numbers.Add (0); numbers.Sort(); var s = String.Join (", ", numbers); Console.WriteLine (s);
//Output Below
0, 2, 6
Great! Again, we can call the Sort ()
method. The list will remain sorted until we add another element.
So, let's see how we can remove an item from a list!
var villains = new List<string> (); villains.Add ("Lex Luthor"); villains.Add ("Magneto"); villains.Add ("Green Goblin"); villains.Remove("Magneto"); var s = String.Join (", ", villains); Console.WriteLine (s);
//Output Below
Lex Luthor, Green Goblin
Nice! The Remove ()
method gets rid of the item we specify. If we want to use the index number instead of the item's value, we can use RemoveAt ()
.
Another method we've seen before! How do we check if our list contains a specific value?
var numbers = new List<int> (); numbers.Add (3); numbers.Add (5); bool b = numbers.Contains(3); Console.WriteLine (b);
//Output Below
True
Nice work! Contains ()
will return a boolean that's true
if the list contains the value and false
if it doesn't.
Here's another method that we'll recognize: it finds the index of a specific value in a list.
var speeds = new List<int> (); speeds.Add (37); speeds.Add (29); speeds.Add (6); var i = speeds.IndexOf (29); var j = speeds.IndexOf (66); Console.WriteLine (i); Console.WriteLine (j);
//Output Below
1 -1
See that? IndexOf ()
finds the first occurrence of a value and returns its index in the list. If the value isn't in the list, the method returns -1
.
At times, adding items one by one can be tiresome. Lucky for us, there's a feature that allows us to create lists from arrays.
int[] array = { 1, 2, 3 }; var list = new List<int> (array); string s = String.Join (", ", list); Console.WriteLine (s);
//Output Below
1, 2, 3
Phew! That way, we get the speediness of arrays and the flexibility of lists.
Don't worry, dictionaries aren't books full of definitions but collections of key-value pairs. Like words pointing to definitions, each key points to a value.
Dictionary<string, int> dict = new Dictionary<string, int> ();
When we create the dictionary, we need to declare the type of the keys and of the values and, of course, give the dictionary a name.
From that point on, we won't be able to use keys or values of a different type.
Unlike lists, we can initialize a dictionary when we declare it. That should save us some time, right?
var dict = new Dictionary<int, string> () { {23, "Michael"}, {91, "Dennis"} };
Whoa! We can put the key-value pairs in braces after the constructor. {23, "Michael"}
is such a pair: 23
is its key and "Michael"
is its value.
Psst: again, if we initialize the dictionary right away, we can use var
instead of Dictionary<string, int>
.
Accessing elements in a dictionary is a little different to arrays and lists. We access a value by using its key.
Dictionary<string, int> dict = new Dictionary<string, int> (); dict.Add ("Ebenezer", 11); dict.Add ("Pippin", 45); dict.Add ("Estella", 37); Console.WriteLine (dict["Ebenezer"]); Console.WriteLine (dict["Estella"]);
//Output Below
11 37
See that? It's not too hard to access values.
It'll be no surprise that we can use the Count
property to find the number of key-value pairs in a dictionary.
Dictionary<string, string> dict = new Dictionary<string, string> () { {"Bob", "London"}, {"Sian" , "New York"} }; Console.WriteLine (dict.Count);
//Output Below
2
Nice! Remember that the .Count
will return the number of pairs not the individual values!
If we want to see all the keys in the dictionary, we can use a simple method to retrieve them as a collection.
var dict = new Dictionary<int, string> () { {4, "Locke"}, {8, "Reyes"} }; var s = String.Join (", ", dict.Keys); Console.WriteLine (s);
//Output Below
4, 8
Sweet! Using the Keys
property with String.Join ()
, we can convert the keys into a string
-type value and write them out.
Similarly, we can use a property to return a collection of values in a dictionary.
var dict = new Dictionary<int, string> () { {4, "Locke"}, {8, "Reyes"} }; var s = String.Join (", ", dict.Values); Console.WriteLine (s);
//Output Below
Locke, Reyes
Simple as that! The Values
property returns a collection of all the values in the dictionary.
Collections like dictionaries and lists seem to have very similar methods and properties. Can you guess the way we add key-value pairs?
var dict = new Dictionary<int, string> (); dict.Add (15, "Ford");
Good job! We've seen the Add ()
method a few times before, haven't we? This time, however, it takes two arguments: a key and a value.
There may be times when we're done with the things we've been storing but want to keep a dictionary for further use.
var dict = new Dictionary<string, string> () { {"Flower", "Power"}, {"Hubble", "Bubble"} }; dict.Clear(); Console.WriteLine (dict.Count);
//Output Below
0
Boom! All we need to do is call Clear ()
on the dictionary and it will part with its key-value pairs.
If only there was a method to see if there's a specific key in a dictionary.
var age = new Dictionary<string, int> () { {"Under 25", 15}, {"Under 35", 12} }; var isThere = age.ContainsKey ("Under 25"); Console.WriteLine (isThere);
//Output Below
True
See that? ContainsKey ()
will return a bool
-type value. If we want to check the same thing with values, we can use ContainsValue ()
instead.
Let's get back to a classic collection method and let go of a key-value pair in this dictionary!
var cSharp = new Dictionary<string, bool> () { {"Fun", true}, {"Boring", false} }; cSharp.Remove ("Boring"); var s = String.Join (", ", cSharp); Console.WriteLine (s);
//Output Below
[Fun, true]
Sweet! As we've seen before, we can use the Remove ()
method; this time, with the key in the parentheses.
C# is a general purpose object-oriented programming language developed at Microsoft and released in 2002. It is similar to Java in its syntax. The purpose of C# is to precisely define a series of operations that a computer can perform to accomplish a task.
Most C# operations involve manipulating numbers and text, but anything that the computer can physically do can be programmed in C#. Computers have no intelligence—they have to be told exactly what to do, and their actions are defined by the programming language you use. Once programmed, they can repeat the steps as many times as needed at high speed. Modern PCs are so fast they can count to a billion in seconds.
Typical programming tasks include putting data into a database or pulling it out, displaying high-speed graphics in a game or video, controlling electronic devices attached to the PC and playing music or sound effects. You can even use it to write software to generate music or help you compose.
Some developers believe that C# is too slow for games because it is interpreted rather than compiled. However the .NET Framework compiles the interpreted code the first time it runs.
C# is a highly ranked program language. Many computer languages are written for a specific purpose, but C# is a general purpose language with features to make programs more robust.
Unlike C++ and to a lesser extent Java, the screen handling in C# is excellent on both desktops and the web. In this role, C# overtook languages such as Visual Basic and Delphi.
Any PC that can run the .NET Framework can run the C# programming language. Linux supports C# using the Mono C# compiler.Don't worry much about.
You need a C# compiler. There are a number of commercial and free ones available. The professional version of Visual Studio can compile C# code. Mono is a free and open-source C# compiler.
C# is written using a text editor. You write a computer program as a series of instructions (called statements ) in a notation that looks a little like mathematical formulas.
This is saved as a text file and then compiled and linked to generate machine code which you then can run. Most applications you use on a computer were written and compiled like this, many of them in C#.
To start building .NET apps you just need to download and install the .NET SDK (Software Development Kit) from Microsoft.
Once you've installed, open a new command prompt(on windows, type cmd in the start menuand right click and click on start as administrator and on linux, press the windows button and T) and run the following command
dotnet
If the command runs, printing out information about how to use dotnet, you're good to go.
In your command prompt, run the following commands
dotnet new console -o myApp
cd myApp
The dotnet command creates a new application of type console for you. The -o parameter creates a directory named myApp where your app is stored, and populates it with the required files. The cd myApp command puts you into the newly created app directory.
The main file in the myApp folder is Program.cs . By default, it already contains the necessary code to write "Hello World!" to the Console.
To run your app ,In your command prompt, run the following command:
dotnet run
Congratulations, you've built and run your first .NET app! you can now add changes to your app by opening the Program.cs in the directory of your app and edit with any text editor of your choice , I recommend Visual Studio code or Gedit .Plus always remember to save in order to see your changes in effect.
A method is a block of statements that performs a specific task.
string str1 = "Look at us "; string str2 = "using a method!"; string str3 = String.Concat (str1, str2);
//Output Below
Look at us using a method!
See that? String.Concat ()
is a built-in method that we've already used. It, well, concatenates strings.
If a method already exists, we just call it when we need it.
Sometimes, however, we want to create custom methods that do things that no built-in method can.
// This goes outside of Main (): static void SayHello() { string s = "Hello World!"; Console.WriteLine (s); } // This goes within Main (): SayHello ();
//Output Below
Hello World!
We start with the static
and void
keywords, a method name and parentheses. The lines in the braces are executed when we call the method.
Do you remember how some of the methods we've used returned values?
If we want a custom method to return something, we need to specify a data type for such a value instead of void
.
static int Triple (int n) { int result = n * 3; return result; } var number = Triple (3); Console.WriteLine (number);
//Output Below
9
Sweet! Methods with a so-called return type have to use the return
keyword to, well, return a value of that type.
Psst: the static
keyword helps us use Triple ()
without creating a so-called object of the class we put it in. We'll talk some more about that later, okay?
Also, there were times when we called methods and put things in the parentheses after their names, right?
If we want a method to accept such parameters, we have to mention that when we create it.
static void SayHello (string name) { string str1 = "Hello "; string str2 = name; Console.WriteLine (str1 + str2); } SayHello ("Hodor");
//Output Below
Hello Hodor
See that? When we call SayHello ()
, we can pass in any value of the parameter's type and it will become a variable within the method.
If we want, we can also use multiple parameters.
int Multiply (int x, int y, int z) { int result = x * y * z; return result; } int number = Multiply (1, 2, 3); Console.WriteLine (number);
//Output Below
6
Sweet! We simply create and call the method with multiple parameters that we separate with commas.
How about something a little more advanced? We use recursion when we have a method call itself inside its code block.
static int Factorial (int number) { int result; if (number == 1) { return 1; } else { result = Factorial (number - 1) * number; return result; } } int factorial = Factorial (5); Console.Write (factorial);
//Output Below
120
Sweet! We can call Factorial ()
recursively to calculate a number's factorial.
Psst: if this still feels a bit too advanced, don't worry; you can come back anytime when you feel ready!
At times we might want to set default parameters for methods. That way, they'll have a default value when we call the method.
static int Multiply (int i, int x = 3) { int result = i * x; return result; } int product = Multiply (10); Console.WriteLine (product);
//Output Below
30
See that? We have to specify a value for i
but we can skip x
when we call Multiply ()
because it has a default value.
Using the params
keyword and an array, we can also have an unlimited number of parameters. The possibilities are endless!
static int Totalize (params int[] numbers) { int result = 0; foreach (int number in numbers) { result += number; } return result; } Totalize (1); Totalize (1, 2, 3);
//Output Below
1 6
See that? From zero to an endless stream of values: there's no limit to how many values, or arguments we can pass to Totalize ()
.
Object-oriented programming is a way to model computer programs by bundling things into objects that interact with each other.
List<int> list = new List<int> (); Console.Write (list.Count);
//Output Below
0
We've already created lots of objects: strings, numbers, lists, dictionaries: in C#, pretty much everything is an object.
Psst: we're slowly moving into serious topics, where everything will come together.
A class is kind of like blueprint of a particular object. It's a group of methods and variables that belong to the object.
List<int> list = new List<int> (); list.Add (42); list.Insert (9000, 1); list.RemoveAt (1); Console.WriteLine (list.Count);
//Output Below
1
Nice! Whenever we create an instance of a class with the new
keyword, we're said to create an object that can use these methods and variables.
Let's dig deeper and create a class! We start with the class
keyword followed by the class's name. Everything we put in the braces becomes a part of the class.
// Outside of the Main class: class Car { string color; void StartEngine () { Console.WriteLine ("Vroom!"); } } // In the Main () method: Car myCar = new Car (); myCar.StartEngine (); myCar.color = "red";
//Output Below
Vroom!
Sweet! This class describes cars with a color
variable and a StartEngine ()
method.
Psst: we didn't have to use the static
keyword for StartEngine ()
because we created an instance of the Car
class.
We've seen constructors throughout the course, haven't we? They're the methods we call when we create an instance of a class.
Car myCar = new Car ();
Sweet! By calling the constructor of the Car
class, we're creating an instance of it that we store in myCar
.
Wouldn't it be great if we could set the color of myCar
when we call the constructor?
class Car { string color; Car (string color) { this.color = color; StartEngine (); } void StartEngine () { Console.Write ("Vroom!"); } } Car myCar = new Car ("red");
//Output Below
Vroom!
Sweet! When we create a method that shares its name with the class, we create a custom constructor, with which we can set values and call methods.
Let's create another class method like StartEngine ()
, okay? This time, however, let's return something!
class Car { // ... (things from before) string GetDetails () { return "This car is " + color; } } Car myCar = new Car ("red"); myCar.GetDetails () ;
//Output Below
This car is red
Sweet! The GetDetails ()
method returns a string
-type value with a brief description of the car.
When we create classes and their members, visibility is important! There are five access specifiers in C#, but all you need right now are public
or private
.
class Car { private string color; public void StartEngine () { Console.Write ("Vroom!"); } } Car myCar = new Car (); myCar.StartEngine ();
private
members can only be accessed in the class
they have been declared. We can't accesscolor
!
public
methods can be accessed from anywhere in the program. We can access.StartEngine ()
!
Like we saw last lesson, we can't access private properties directly from outside the class.
Instead, we use a public property with get and set accessors.
class Car { private string color; public string Color { get { return color; } set { color = value; } } } Car vehicle = new Car (); vehicle.Color = "Blue"; Console.Write (vehicle.Color);
//Output Below
Blue
As you'd expect, get
allows us to get the property with .color
, and set
allows us to set it with .color =
.
Inheritance is a very useful feature of classes. With it, we can reuse things when classes aren't that different.
class Vehicle { public int wheels = 4; public string brand = "Ford"; } class Car : Vehicle { public string GetDetails () { return "This is a " + brand + " with " + wheels " wheels"; } } Car myCar = new Car (); Console.Write (myCar.GetDetails ());
//Output Below
This is a Ford with 4 wheels
Handy! The Car
class, which is the derived class in this case, inherits everything from Vehicle
, its base class.
Psst: we can also override things by redefining them in the derived class using the keyword override
.
In this lesson, let's get back to that mysterious Main ()
method!
As we've seen, Main ()
is the entry point of any program we write.
using System; namespace App { class Program { public static void Main(string[] args) { SayHi (); } static void SayHi () { Console.WriteLine ("Hi!"); } } }
//Output Below
Hi!
Sweet! "Hi!"
would never show if we didn't have a Main ()
method in a class that calls it.
As we've seen, static methods and variables can be used without creating an instance of the class they're in.
public static void Main (string[] args) { SayHi (); } static void SayHi () { Console.WriteLine ("Hi!"); }
//Output Below
Hi!
It's important for Main ()
to be static because it's at the very beginning of the program.
Psst: why didn't we create an instance of the Console
class when we called the WriteLine ()
method? Well, because WriteLine ()
is a static method as well!
Have you noticed how Main ()
always includes a string array called args
as a parameter?
MyApp.exe Richard Erlich public static void Main (string[] args) { foreach (string arg in args) { Console.WriteLine (arg); } }
//Output Below
Richard Erlich
See that? args
contains the command-line arguments we may or may not pass to the program when we execute it through, well, the command line.
So how do we get Car
, or other classes we created, to work? Might Main ()
be the key?
/* Car.cs */ using System; class Car { private string color; public Car (string color) { this.color = color; } public void StartEngine () { Console.Write ("Vroom!"); } }/* Program.cs */ using System; class Program { public static void Main (string[] args) { var c = new Car ("red"); } }
Sweet! We create Program
, the application class, with a Main ()
method that creates an instance of the Car
class, which we describe in a separate file.
Do you remember the namespace
keyword from the early days? Namespaces help us structure projects into meaningful pieces.
using System; namespace Classes { class Car { private string color; public Car (string color) { this.color = color; } public void StartEngine () { Console.Write ("Vroom!"); } } } using System; namespace App { class Program { public static void Main (string[] args) { var c = new Classes.Car("red"); } } }
Sweet! With a namespace, we can provide hints about the purpose of the classes it contains and distinguish between classes with the same name.
So, what about that using
keyword that seems to be at the beginning of every class?
using System; namespace App { class Program { public static void Main (string[] args) { Console.Write ("Hi!"); } } }
//Output Below
Hi!
See that? Console
belongs to the System
namespace. Whenever we call the Write ()
method, we're actually calling System.Console.Write ()
.
Psst: if we add the using
keyword with System
at the top, we don't have to type System
every time we use something from that namespace.
Sometimes we have to access nested namespaces. The List
class, for example, is defined in System.Collections.Generic
.
using System.Collections.Generic; namespace App { class Program { public static void Main (string[] args) { var n = new System.Collections.Generic.List<int> (); var m = new List<int> (); n.Add(8); m.Add(1); m.Add(n[0]); string s = String.Join (", ", m); Console.Write (s); } } }
//Output Below
1, 8
Yass? With the using
statement in place, we can but don't have to use the List
class's namespace hierarchy when we use it.
So we've learned about the Main ()
method and how classes and namespaces work with it.
using System; namespace App { class Program { public static void Main (string[] args) { var a = new Animal ("Sparky", "dog"); var s = sparky.Describe (); Console.Write (s); } } } using System; namespace App{ class Animal { private string name; private string species; public Animal (string name, string species) { this.name = name; this.species = species; } public string GetDetails () { var s = name + ", " + species; return s; } } }
Fantastic! It makes perfect sense for the classes to be in the same namespace. Also, it makes their usage a lot more convenient.