From 8c4a02784bb09e3c1af62cfd10b089023a509f13 Mon Sep 17 00:00:00 2001 From: borb Date: Thu, 3 Jul 2025 15:22:23 +0300 Subject: [PATCH] finish lecture 3, update lecture 7 --- 3-conditionals-slides.html | 373 ++++++++++++++++++++++++++++ 3-conditionals.md | 397 ++++++++++++++++-------------- 7-classes-and-objects-slides.html | 84 ++++--- 7-classes-and-objects.md | 41 +-- 4 files changed, 666 insertions(+), 229 deletions(-) create mode 100644 3-conditionals-slides.html diff --git a/3-conditionals-slides.html b/3-conditionals-slides.html new file mode 100644 index 0000000..e19c8e9 --- /dev/null +++ b/3-conditionals-slides.html @@ -0,0 +1,373 @@ +3. Conditionals
+

Conditionals

+
+
+

Overview

+
    +
  • Conditionals
  • +
  • if and else
  • +
  • Logical Operators
  • +
+
+
+

Comparison operators

+
    +
  • Comparison operators are used to compare two variables +
      +
    • They return either true or false
    • +
    +
  • +
  • Two variables of any type can be compared with equality operators +
      +
    • Equal to: a == b +
        +
      • (Do not mix with the assignment operator, see Lecture 2!)
      • +
      +
    • +
    • Not equal to: a != b
    • +
    +
  • +
  • Two numbers can be further compared with less than/greater than operators: +
      +
    • Less than: a < b
    • +
    • Less than or equal: a <= b
    • +
    • Greater than: a > b
    • +
    • Greater than or equal: a >= b
    • +
    +
  • +
+
+
+

bool data type

+
    +
  • As shown in Lecture 2, bool is a data type for storing truth values true or false
  • +
  • Because conditionals return true or false, the result can be stored in a variable
    int a = 4;
    +int b = 3;
    +bool areEqual = a == b;   // outputs False
    +bool biggerOrNot = a > b; // outputs True
    +
    +
  • +
  • Useful for making multiple comparisons at once
  • +
+
+
+

if, else if and else statements

+
+
+
    +
  • if checks truthfulness of a given statement
  • +
  • If it results in false, we can check if another condition is met with else if
  • +
  • Multiple else if can be chained indefinitely
  • +
  • If no statement returns true, the else block is executed
  • +
  • The statements are checked in order, and the first true condition is executed +
      +
    • No other block is executed
    • +
    +
  • +
  • (You can also have just if and else without the else if, or just a single if.)
  • +
+
+
+
int a = 2
+if (a > 4)
+{
+  // do something
+}
+else if (a < 2)
+{
+  // do something else
+}
+else if (a < 3)
+{
+  // do something else
+}
+else
+{
+  // a is 4??
+}
+
+
+
+
+
+

Conditionals: An example

+
double temperatureInOulu = 2.3;
+double temperatureInIvalo = -10.9;
+if (temperatureInOulu > temperatureInIvalo)
+{
+  Console.WriteLine("Oulu is warmer than Ivalo");
+}
+else if (temperatureInOulu < temperatureInIvalo)
+{
+  Console.WriteLine("Ivalo is warmer than Oulu");
+}
+else
+{
+  Console.WriteLine
+    ("Oulu and Ivalo have the same temperature");
+}
+
+

This outputs Oulu is warmer than Ivalo.

+
+
+

Not operator !

+
    +
  • The ! ("not") operator flips the boolean value.
  • +
+
Console.WriteLine(!true);     // Outputs false
+bool itsColdOutside = true;
+if (!itsColdOutside)          // same as checking if (itsColdOutside == false)
+{
+  Console.WriteLine("It's warm outside.");
+}
+
+
+
+

The switch statement

+
+
+
    +
  • The switch statement compares the given expression (in this example, the path variable) with the value of each case
  • +
  • Only the matching code is executed
  • +
  • If no match is found, the default code block is executed
  • +
  • This example outputs Here's the catalogue!
  • +
  • break ends each case (the code will not compile if omitted!)
  • +
+
+
+
string path = "/browse";
+
+switch (path)
+{
+  case "/browse":
+    Console.WriteLine("Here's the catalogue!");
+    break;
+  case "/contact":
+    Console.WriteLine("Here's our contact info.");
+    break;
+  default:
+    Console.WriteLine("Given path doesn't exist!");
+    break;
+}
+
+
+
+
+
+

Scope of Variables

+
    +
  • Variables declared inside of blocks {} are local to that scope; they are only accessible inside of that block
    if (true)
    +{
    +  int b = 1;        // b is only accessible in this block
    +  b = 2;            // This works
    +}
    +
    +b = 3;              // This throws an error
    +
    +
  • +
  • Similarly, classes are only defined inside their namespace, and have to be imported to be accessible elsewhere
  • +
  • Note: Some languages have global variables that are accessible everywhere — as an object-oriented language, C# doesn't have such feature.
  • +
+
+
+

Logical Operators

+
    +
  • &&, || and ! are the logical AND, OR and NOT operators
  • +
  • These are useful when writing complex if statements
  • +
+
+
+
int a = 1;
+int b = 3;
+int c = 5;
+if (a < 10)
+{
+  if (b < 10)
+  {
+    if (c < 10)
+    {
+      Console.WriteLine
+        ("All are smaller than 10!")
+    }
+  }
+}
+
+
+
+
int a = 1;
+int b = 3;
+int c = 5;
+if (a < 10 && b < 10 && c < 10)
+{
+  Console.WriteLine
+    ("All are smaller than 10!")
+}
+
+
    +
  • Same functionality achieved in fewer lines!
  • +
+
+
+
+
+

Common logical operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameUsageDescription
&&ANDa && bReturns true if both variables are true.
b is not evaluated if a == false.
||ORa || bReturns true if one or both variables are true.
b is not evaluated if a == true.
!NOT!aNegates the boolean value.
(true becomes false and vice versa).
+
+
+

Less common logical operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameUsageDescription
^XORa ^ b  Exclusive OR ("joko tai"): returns true if only either of a or b are true, but not both!
&Logical ANDa & bReturns true if both variables are true.
Both variables are always evaluated.
|Logical ORa | bReturns true if one or both variables are true.
Both variables are always evaluated.
+
+
+

Logical operators: An Example

+
int uppercaseLetters = 2;
+uppercaseLetters += 4;          // is now 6
+
+int specialCharacters = 2;
+specialCharacters *= 2;         // is now 4
+
+if (uppercaseLetters >= 6 && specialCharacters >= 2)
+{
+  Console.WriteLine("Strong password!");
+}
+else
+{
+  Console.WriteLine("Weak password...");
+}
+
+

This outputs Strong password!

+
+
+

Extra: Single statement if

+ +
    +
  • If a code block following a statement only has one line of code, it is possible to write the block without curly brackets:
    int baa = 49;
    +if (baa > 20)
    +  Console.WriteLine("Baa");
    +else
    +  Console.WriteLine("Not baa!");
    +if (baa > 20) Console.WriteLine("Baa");
    +else Console.WriteLine("Not baa!");
    +
    +
  • +
  • You may encounter code like this — however, we highly recommend to refrain from using this syntax as it is highly prone to errors. +
      +
    • Can you guess how this syntax can lead to bugs?
    • +
    +
  • +
+
+
+

Exercise 1

+ +
    +
  1. Create a console application that asks the user which weekday it is and assigns the answer to a string variable.
  2. +
  3. Using a switch-case expression, calculate the days remaining until next Monday.
  4. +
  5. If the result is more than 3, print Have a nice week!. Otherwise, print Have a nice weekend!.
  6. +
+
+
+

Exercise 2

+ +
    +
  1. Create a console application that lets the user input a note as a string.
  2. +
  3. If the length of the note is less than 30, the program prints the current time and the note separated by a tab. Otherwise, the date and the note are printed to a separate line.
  4. +
+

Tip: Use DateTime.Now.ToString() for current time. Use .Length after your message variable to get the length of the message.

+
+
+

Reading

+

Basics covering the syntax in C# are covered here:

+ +
+
+

Assignments

+ +

Assignments about this topic can be found here

+
+

| Comparison | Syntax | +|:-------------------------|:---------| +| Less than | `a < b` | +| Less than or equal to | `a <= b` | +| Greater than | `a > b` | +| Greater than or equal to | `a >= b` | +| Equal to | `a == b` | +| Not equal to | `a != b` |

\ No newline at end of file diff --git a/3-conditionals.md b/3-conditionals.md index 4dcc737..8ece8af 100644 --- a/3-conditionals.md +++ b/3-conditionals.md @@ -1,263 +1,302 @@ -# Conditionals - -![](imgs/3%20Conditionals_0.png) - --- - -# Overview - -Conditionals - -if and else - -Logical Operators +marp: true +paginate: true +math: mathjax +theme: buutti +title: 3. Conditionals +--- # Conditionals -Less than: a < b - -Less than or equal to: a <= b - -Greater than: a > b - -Greater than or equal to: a >= b - -Equal to a == b - -Not Equal to: a != b + + + +## Overview + +* Conditionals +* `if` and `else` +* Logical Operators + +## Comparison operators + +* ***Comparison operators*** are used to compare two variables + * They return either `true` or `false` +* Two variables of any type can be compared with equality operators + * Equal to: `a == b` + * (Do not mix with the assignment operator, see [Lecture 2](2-variables-and-types#assignment-operators)!) + * Not equal to: `a != b` +* Two ***numbers*** can be further compared with less than/greater than operators: + * Less than: `a < b` + * Less than or equal: `a <= b` + * Greater than: `a > b` + * Greater than or equal: `a >= b` + + + +### `bool` data type + +* As shown in [Lecture 2](2-variables-and-types#primitive-data-types), `bool` is a data type for storing truth values `true` or `false` +* Because conditionals return `true` or `false`, the result can be stored in a variable + ```csharp + int a = 4; + int b = 3; + bool areEqual = a == b; // outputs False + bool biggerOrNot = a > b; // outputs True + ``` +* Useful for making multiple comparisons at once + +## `if`, `else if` and `else` statements + +
+
+ +* `if` checks truthfulness of a given statement +* If it results in `false`, we can check if another condition is met with `else if` +* Multiple `else if` can be chained indefinitely +* If no statement returns `true`, the `else` block is executed +* The statements are checked in order, and the first `true` condition is executed + * No other block is executed +* (You can also have just `if` and `else` without the `else if`, or just a single `if`.) + +
+
+ +```csharp +int a = 2 +if (a > 4) +{ + // do something +} +else if (a < 2) +{ + // do something else +} +else if (a < 3) +{ + // do something else +} +else +{ + // a is 4?? +} +``` -Conditionals return true or false, meaning the result can even be allocated into a variable if needed +
+
-bool areEqual = (a == b); -# if , else and else if statements +### Conditionals: An example +```csharp double temperatureInOulu = 2.3; - double temperatureInIvalo = -10.9; - if (temperatureInOulu > temperatureInIvalo) - { - -Console.WriteLine("Oulu is warmer than Ivalo"); - + Console.WriteLine("Oulu is warmer than Ivalo"); } - else if (temperatureInOulu < temperatureInIvalo) - { - -Console.WriteLine("Ivalo is warmer than Oulu"); - + Console.WriteLine("Ivalo is warmer than Oulu"); } - else - { - -Console.WriteLine - -("Oulu and Ivalo have the same temperature"); - + Console.WriteLine + ("Oulu and Ivalo have the same temperature"); } +``` -__if __ statements are executed in order - -The first statement with a __true __ condition is executed - -If no statement holds a true value, __else __ is executed +This outputs `Oulu is warmer than Ivalo`. -This outputs "Oulu is warmer than Ivalo" - -# ! -Operator - -Console.WriteLine(!true); // Outputs false +## Not operator `!` +* The `!` ("not") operator flips the boolean value. +```csharp +Console.WriteLine(!true); // Outputs false bool itsColdOutside = true; - -if(!itsColdOutside) - +if (!itsColdOutside) // same as checking if (itsColdOutside == false) { - -Console.WriteLine("It's warm outside."); - + Console.WriteLine("It's warm outside."); } +``` -The ! -operator flips the boolean value __ __ +## The `switch` statement -# The switch statement +
+
-The __switch __ statement compares the parameter value (here: the __path __ variable) with the value of each __case__ +* The `switch` statement compares the given expression (in this example, the `path` variable) with the value of each `case` +* Only the matching code is executed +* If no match is found, the default code block is executed +* This example outputs `Here's the catalogue!` +* `break` ends each case (the code will not compile if omitted!) -Only the matching code is executed - -If no match is found, the default code block is executed - -This outputs "Here's the catalogue!" - -break ends the case and exits the switch: the code will not compile if omitted +
+
+```csharp string path = "/browse"; switch (path) - { - -case "/browse": - -Console.WriteLine("Here's the catalogue!"); - -break; - -case "/contact": - -Console.WriteLine("Here's our contact info."); - -break; - -default: - -Console.WriteLine("No such path!"); - -break; - + case "/browse": + Console.WriteLine("Here's the catalogue!"); + break; + case "/contact": + Console.WriteLine("Here's our contact info."); + break; + default: + Console.WriteLine("Given path doesn't exist!"); + break; } +``` -# Scope of Variables - -Variables declared inside of blocks are called __local variables__ ; they are only accessible inside of that block. +
+
-int a = 0; +## Scope of Variables -if(a < 10) +* Variables declared inside of blocks `{}` are ***local*** to that ***scope***; they are only accessible inside of that block + ```csharp + if (true) + { + int b = 1; // b is only accessible in this block + b = 2; // This works + } -{ + b = 3; // This throws an error + ``` +* Similarly, classes are only defined inside their `namespace`, and have to be imported to be accessible elsewhere +* ***Note:*** Some languages have `global` variables that are accessible everywhere — as an object-oriented language, C# doesn't have such feature. -// Variable 'b' is only accessible inside of this if block +## Logical Operators -int b = 1; +* `&&`, `||` and `!` are the logical AND, OR and NOT operators +* These are useful when writing complex `if` statements -b = 2; // This works +
+
+```csharp +int a = 1; +int b = 3; +int c = 5; +if (a < 10) +{ + if (b < 10) + { + if (c < 10) + { + Console.WriteLine + ("All are smaller than 10!") + } + } } +``` -b = 3; // This throws an error - -# Assignment Operators - -We have used the assignment operator ' __='__ for assigning values for variables: - -int x; - -x = 25; - -__Notice __ the difference between '=' and the conditional '=='! - -'=' is used for assigning values for variables, '== is used for comparing values - -# Logical Operators - -'&&', '||' and '!' mean the logical AND, OR and NOT operators - -For example, +
+
+```csharp int a = 1; - int b = 3; - int c = 5; +if (a < 10 && b < 10 && c < 10) +{ + Console.WriteLine + ("All are smaller than 10!") +} +``` +* Same functionality achieved in fewer lines! -Console.WriteLine(a < b && a < c); +
+
-outputs "True" +### Common logical operators -| Operator | Name | Example | Description | -| :-: | :-: | :-: | :-: | -| && | AND | a && b | Returns true if __both__ variables are true.b is not evaluated if a == false. | -| || | OR | a || b | Returns true if __one or both__ variables are true. b is not evaluated if a == true. | -| ! | NOT | !a | __Negates__ boolean value (true becomes false and vice versa) | -| ^ | XOR | a ^ b | Exclusive OR: returns true if __only __ a == true __OR only__ b == true. | -| & | Logical AND | a & b | Returns true if __both__ variables are true. Both variables are always evaluated. | -| | | Logical OR | a | b | Returns true if __one or both__ variables are true.Both variables are always evaluated. | +| Operator | Name | Usage | Description | +|:---------|:-----|:-----------|:-----------------------------------------------------------------------------------------| +| `&&` | AND | `a && b` | Returns `true` if *__both__* variables are true.
`b` is not evaluated if `a == false`. | +| `\|\|` | OR | `a \|\| b` | Returns `true` if *__one or both__* variables are true.
`b` is not evaluated if `a == true`. | +| `!` | NOT | `!a` | Negates the boolean value.
(`true` becomes `false` and vice versa). | ---- +### Less common logical operators -Tässä on kaikki aritmeettiset operaattorit +| Operator | Name | Usage | Description | +|:---------|:------------|:---------|:-----------------------------------------------------------------------------------------| +| `^` | XOR | `a ^ b`   | Exclusive OR ("*joko tai*"): returns `true` if *__only either of__* `a` or `b` are `true`, but not both! | +| `&` | Logical AND | `a & b` | Returns `true` if __both__ variables are `true`.
Both variables are always evaluated. | +| `\|` | Logical OR | `a \| b` | Returns `true` if __one or both__ variables are `true`.
Both variables are always evaluated. | -# Operators - Example +### Logical operators: An Example -This outputs "Strong password!" +```csharp int uppercaseLetters = 2; - uppercaseLetters += 4; // is now 6 int specialCharacters = 2; - specialCharacters *= 2; // is now 4 if (uppercaseLetters >= 6 && specialCharacters >= 2) - { - -Console.WriteLine("Strong password!"); - + Console.WriteLine("Strong password!"); } - else - { - -Console.WriteLine("Weak-ass password..."); - + Console.WriteLine("Weak password..."); } +``` +This outputs `Strong password!` -# Exercise 1: +## Extra: Single statement `if` + -Create a console application which asks the user which weekday it is and assigns the answer to a string variable. +* If a code block following a statement only has one line of code, it is possible to write the block ***without*** curly brackets: + ```csharp + int baa = 49; + if (baa > 20) + Console.WriteLine("Baa"); + else + Console.WriteLine("Not baa!"); + if (baa > 20) Console.WriteLine("Baa"); + else Console.WriteLine("Not baa!"); + ``` +* You may encounter code like this — however, we highly recommend to refrain from using this syntax as it is highly prone to [errors](https://www.leadingagile.com/2018/01/the-goto-fail-bug-as-a-coaching-tool/). + * Can you guess how this syntax can lead to bugs? -Using a switch-case, calculate the days remaining until next Monday. - -If the result is more than 3, print "Have a nice week!". Otherwise, print "Have a nice weekend!". - -# Exercise 2: - -Create a console application which lets the user input a note. - -If the length of the note is less than 30, the program prints the current time and the note, separated with a tab. Otherwise, the date and the note are printed to a separate line. - -Tip: Use DateTime.Now.ToString() for current time. Use .Length after your message variable to get the length of the message. - -# One More Thing... - -If a code block following a statement only has one line of code, you can write the code without using curly brackets: - -int baa = 49; - -if (baa > 20) - -Console.WriteLine("Baa"); - -else +## Exercise 1 + -Console.WriteLine("Not baa!"); +1) Create a console application that asks the user which weekday it is and assigns the answer to a string variable. +2) Using a switch-case expression, calculate the days remaining until next Monday. +3) If the result is more than 3, print `Have a nice week!`. Otherwise, print `Have a nice weekend!`. -if (baa > 20) Console.WriteLine("Baa"); +## Exercise 2 + -else Console.WriteLine("Not baa!"); +1) Create a console application that lets the user input a note as a string. +2) If the length of the note is less than 30, the program prints the current time and the note separated by a tab. Otherwise, the date and the note are printed to a separate line. -You may see code where this is done. However, we highly recommend you not to use this syntax as it is highly prone to [errors](https://www.leadingagile.com/2018/01/the-goto-fail-bug-as-a-coaching-tool/) . +***Tip:*** Use `DateTime.Now.ToString()` for current time. Use `.Length` after your message variable to get the length of the message. -# Get Help -All the basics covering the syntax in C# are covered here: +## Reading -[https://www.tutorialspoint.com/csharp/index.](https://www.tutorialspoint.com/csharp/index.htm) [htm](https://www.tutorialspoint.com/csharp/index.htm) [l](https://www.tutorialspoint.com/csharp/index.htm) +Basics covering the syntax in C# are covered here: -[https://www.w3schools.com/cs/default.asp](https://www.w3schools.com/cs/default.asp) +* [Learn .NET: C# Documentation](https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/) +* [Tutorialspoint: C# tutorial](https://www.tutorialspoint.com/csharp/index.htm) +* [W3Schools: C# tutorial](https://www.w3schools.com/cs/default.asp) -# Assignments +## Assignments + [Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/3.%20Conditionals) diff --git a/7-classes-and-objects-slides.html b/7-classes-and-objects-slides.html index b20f632..0902a90 100644 --- a/7-classes-and-objects-slides.html +++ b/7-classes-and-objects-slides.html @@ -13,10 +13,10 @@ /* buutti.css */ /* @theme buutti */div#\:\$p>svg>foreignObject>section .columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns12{display:grid;grid-template-columns:1fr 2fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns21{display:grid;grid-template-columns:2fr 1fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns32{display:grid;grid-template-columns:3fr 2fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns23{display:grid;grid-template-columns:2fr 3fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns111{display:grid;grid-template-columns:1fr 1fr 1fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .centered{display:flex;flex-direction:column;justify-content:center;text-align:center}div#\:\$p>svg>foreignObject>section .tableborderless td,div#\:\$p>svg>foreignObject>section th{border:none!important;border-collapse:collapse}div#\:\$p>svg>foreignObject>section.extra{background-color:#5d275d;background-image:linear-gradient(to bottom,#401a40,#1d0c1d);color:white}div#\:\$p>svg>foreignObject>section.extra a{color:rgb(145,255,209)}div#\:\$p>svg>foreignObject>section.exercise{background-color:#29366f;background-image:linear-gradient(to bottom,#20636a,#173742);color:white}div#\:\$p>svg>foreignObject>section.exercise a{color:rgb(211,173,255)} -/* @theme ms8msnm58am9pdu7xroo9cceafwjshqw5mpy0cz5gqe */div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]{columns:initial!important;display:block!important;padding:0!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:before,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:before{display:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]{all:initial;display:flex;flex-direction:row;height:100%;overflow:hidden;width:100%}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container][data-marpit-advanced-background-direction=vertical]{flex-direction:column}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split]>div[data-marpit-advanced-background-container]{width:var(--marpit-advanced-background-split,50%)}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split=right]>div[data-marpit-advanced-background-container]{margin-left:calc(100% - var(--marpit-advanced-background-split, 50%))}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure{all:initial;background-position:center;background-repeat:no-repeat;background-size:cover;flex:auto;margin:0}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure>figcaption{position:absolute;border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;white-space:nowrap;width:1px}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content],div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo]{background:transparent!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo],div#\:\$p>svg[data-marpit-svg]>foreignObject[data-marpit-advanced-background=pseudo]{pointer-events:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background-split]{width:100%;height:100%}
+/* @theme 9mp64rqthc45fzsyh9lzvi0j0f2d35s76theih2ughm */div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]{columns:initial!important;display:block!important;padding:0!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:before,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:before{display:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]{all:initial;display:flex;flex-direction:row;height:100%;overflow:hidden;width:100%}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container][data-marpit-advanced-background-direction=vertical]{flex-direction:column}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split]>div[data-marpit-advanced-background-container]{width:var(--marpit-advanced-background-split,50%)}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split=right]>div[data-marpit-advanced-background-container]{margin-left:calc(100% - var(--marpit-advanced-background-split, 50%))}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure{all:initial;background-position:center;background-repeat:no-repeat;background-size:cover;flex:auto;margin:0}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure>figcaption{position:absolute;border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;white-space:nowrap;width:1px}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content],div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo]{background:transparent!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo],div#\:\$p>svg[data-marpit-svg]>foreignObject[data-marpit-advanced-background=pseudo]{pointer-events:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background-split]{width:100%;height:100%}

Classes And Objects

-
+

Overview

  • Namespaces
  • @@ -28,7 +28,7 @@
  • Value & Reference Types
-
+

Namespaces

  • Using namespaces helps you to organize the scope of your project, so that... @@ -44,7 +44,7 @@
  • By default, when creating a new project and adding classes in Visual Studio, everything is contained within a namespace named after your project name
-
+
  • If you need a class, interface, etc to be accessible from anywhere, create it within that namespace and set it as public
@@ -74,7 +74,7 @@
  • Wait, what's a class, though?
  • -
    +

    Classes

    • Classes in C# are blueprints for specific kinds of collections of data & functionality
    • @@ -91,7 +91,7 @@
    -
    +

    Why classes?

    • Classes are a core feature of the object-oriented programming paradigm popularized by Java in the 90s @@ -105,7 +105,7 @@
    • Shorter files can also mean that it's hard to find the actual functionality from hundreds of short files full of intermediate classes and class factories
    -
    +

    Creating a class

    • You can create a new class by writing
      class Student
      @@ -124,7 +124,7 @@
       
    • These variables declared directly inside classes are called fields.
    -
    +

    Instancing a class

    @@ -157,7 +157,7 @@
    -
    +

    Object variables

    • Variables inside of an object can be accessed with the . operator
    • @@ -188,7 +188,7 @@ Student class:
    -
    +

    Let's fix the previous example by changing the access specifier of the variable id to public:

    @@ -215,34 +215,46 @@ Student class:
  • The value of the variable id of the object student is now 12345678
  • -
    -

    Access Specifiers

    +
    +

    Access modifiers

    +
    +
      -
    • Access specifiers can be used to get additional level of protection inside classes
    • -
    • Variables specified with private are accessible only inside the containing class +
    • Access modifiers can be used to get additional level of protection inside classes
    • +
    • private: accessible only inside the containing class
        -
      • This is the default access!
      • +
      • This is the default, but we can make it more explicit by writing it out
    • -
    • Variables specified with public are accessible outside of the class
      class Student
      +
    • public: accessible everywhere in the namespace
    • +
    • Less common, but good to know: +
        +
      • protected: like private, but also accessible by the inheritors of the class
      • +
      • virtual: accessible and overridable by inheritors
      • +
      +
    • +
    +
    +
    +
    class Student
     {
    -  int id;                 // Accessible only inside the class
    -  private string name;    // Accessible only inside the class
    -  public string address;  // Accessible everywhere within the namespace
    +  int id;
    +  private string name;
    +  public string address;
     }
     
    - - +
    +
    -
    +
    • -

      Continuing on the class in the previous example: if we follow the student variable with a dot, Visual Studio IntelliSense will only suggest the address variable, because it was the only public variable of the Student class!

      +

      Continuing on the class in the previous example: if we follow the student variable with ., Visual Studio IntelliSense will only suggest the address variable, because it was the only public variable of the Student class!

    -
    +

    Classes: An example

    @@ -274,7 +286,7 @@ Student class:
    -
    +

    Exercise 1

      @@ -283,7 +295,7 @@ Student class:
    1. Print all stored usernames every time a new user is created
    -
    +

    Class methods

    • As mentioned in Lecture 6, we can create methods inside of our classes:
    • @@ -320,7 +332,7 @@ Student class:
    • If the method is public, it can be called from outside of the class
    -
    +

    Constructors

    • Constructors are class methods which are called once the object is initialized
    • @@ -354,7 +366,7 @@ Student class:
    • Note: In Visual Studio, just write ctor and press tab twice to quickly create a constructor!
    -
    +

    Constructors with parameters

    • You can pass in parameters to the constructor at initialization:
    • @@ -390,7 +402,7 @@ Student class:
    -
    +

    Exercise 2

      @@ -404,7 +416,7 @@ Student class:
    1. Call their greet methods from the main program
    -
    +

    Properties

    • When working with C#, you will eventually see properties being used at some point
    • @@ -441,7 +453,7 @@ Student class: }
    -
    +

    Auto Properties

    • Auto properties are a shorthand version of the same:
    • @@ -472,7 +484,7 @@ Student class:
    • Note: In Visual Studio, just write prop and press tab twice to quickly create an auto property
    -
    +

    Why properties?

    • Why use properties if we could just use public fields?
    • @@ -493,7 +505,7 @@ Student class:
    -
    +

    Value and Reference Types

    • See the example below. If this program is executed, what will be the output?
    • @@ -522,7 +534,7 @@ Student class:
    -
    +
    • Another example: When this program is executed, what will be the output?
    • string, Array and Classes are of the *reference type @@ -558,10 +570,10 @@ Student class:
    -
    +

    -
    +

    Exercise 3

      diff --git a/7-classes-and-objects.md b/7-classes-and-objects.md index a8f69f0..bcadbcc 100644 --- a/7-classes-and-objects.md +++ b/7-classes-and-objects.md @@ -220,24 +220,37 @@ class Program * The value of the variable `id` of the object `student` is now `12345678` -## Access Specifiers +## Access modifiers -* *__Access specifiers__* can be used to get additional level of protection inside classes -* Variables specified with `private` are accessible only inside the containing class - * This is the ***default*** access! -* Variables specified with `public` are accessible outside of the class - ```csharp - class Student - { - int id; // Accessible only inside the class - private string name; // Accessible only inside the class - public string address; // Accessible everywhere within the namespace - } - ``` +
      +
      + +* [Access modifiers](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers) can be used to get additional level of protection inside classes +* `private`: accessible only inside the containing class + * This is the default, but we can make it more explicit by writing it out +* `public`: accessible everywhere in the namespace +* Less common, but good to know: + * `protected`: like `private`, but also accessible by the *inheritors* of the class + * `virtual`: accessible and *overridable* by inheritors + +
      +
      + +```csharp +class Student +{ + int id; + private string name; + public string address; +} +``` + +
      +
      --- -* Continuing on the class in the previous example: if we follow the `student` variable with a dot, Visual Studio IntelliSense will only suggest the `address` variable, because it was the only `public` variable of the `Student` class! +* Continuing on the class in the previous example: if we follow the `student` variable with `.`, Visual Studio IntelliSense will only suggest the `address` variable, because it was the only `public` variable of the `Student` class! ![](imgs/7%20Classes%20and%20Objects_3.png)