🔥Getting Started With C# Part 1[Overview & Control Flow]🔥

Kevin Comba Gatimu
13 min readNov 23, 2022

--

C# basics[overview & control flow]

Session 1: Types, Keywords, and Operators with C#

In this first session, we’re going to start learning about object-oriented programming with C#. We’ll touch on the very basics around variable types, language keywords, and how we can use operators to make variables work together for us.

Get C# to run locally

You can get all of the tools to build with C# locally on your Mac or PC by installing Visual Studio or Visual Studio for Mac. You can also install just the build tools for Windows, Mac, or Linux by following the instructions at dot.net For most of my streams to start, we will be writing code using Jupyter Notebooks and .NET Interactive.

⌛What is C# ?

C# is a statically-typed, compiled, object-oriented language used with the .NET frameworks and runtimes. The official Microsoft C# language reference can be found on docs.microsoft.com. Similar to Java in syntax and structure, C# programs are compiled and executed against a .NET runtime running on a computer. The output of compiling C# code can be called a ‘.NET program’.

A .NET Runtime is a collection of commands native to the computer operating system that instruct the computer how to interpret and run a .NET program

There are several different .NET runtimes available that give C# flexibility to run in many different locations.

➡️.NET Framework — runs on Windows and support desktop user-interface, console, and server development

➡️.NET Core — runs on Windows, Mac, and Linux with support for desktop userinterface, console, and server development

➡️.NET Core — runs on Windows, Mac, and Linux with support for desktop userinterface, console, and server development

➡️Unity — runs on Windows, Mac, Linux, iOS, and Android devices with support for game development using the Unity3D tools

➡️Mono — runs on Windows, Mac, Linux, and Web Assembly

A .NET Framework is a collection of programming instructions and tools that help you write a program of a specific type. Examples of .NET Frameworks include Windows Forms, ASP.NET, Xamarin iOS, and Blazor

C# requires a .NET runtime and frameworks for the appropriate program type to run. The definition of the framework and runtime for a C# program are stored in a .csproj file. We’ll learn more about this file and structure in a future lesson. For now, know that the .NET tools will help construct and manage this file for you when you specify what type of program you want to create.

All C# files carry a .cs file extension by default

Syntax 101⭐

Here are the basics of C# code syntax that you should know as we get started.

⭐C# uses a semi-colon to denote the end of a statement.

This is a hard and fast rule, and you’ll get used to it quickly. Every statement in C# needs to end with a semi-colon ; This allows us to also have very flexible spacing in how we structure our code.

⭐C# is NOT space sensitive

You can place as many spaces, tabs, or blank lines around your code as you would like.

⭐C# IS case sensitive

C# is case-sensitive. All variables, objects, and their interactions must be referenced with the proper casing.

⭐Comment Syntax

You can write comments by using the two forward-slash characters to indicate everything after them is a comment.

// This is a comment
Console.WriteLine("Heey kevin");
output⬇️
Heey kevin

You can create comments that span multiple lines by using slash asterisk fencing like the following:

/* This is a multi-line comment 
sdgdfhdfhdfghdfghdfhdfhdfhd and
this is still commented out */

Everything in C# is an object

As C# is an object oriented language, everything we want to work with is an object. Objects can be declared of various TYPES and then interacted with. The simplest types in C# are called Built-In Types We can define variables, in-memory storage for a type by preceeding the name of the variable we would like to create with the type of the variable we are creating.

int i;
double j;
char c;
Console.WriteLine(c);

That’s not very exciting, but we created a 32-bit integer named i. We can initialize a variable with an = assignment at the time of declaration

The var keyword

Sometimes, its a little cumbersome to declare a variable, assign a value, and have to specify the type before it. C# has built-in type inference and you can use the var keyword to force the compiler to detect the actual type being created and set the variable to the type of the value being assigned.

var i = 10;
var someReallyLongVariableName = 9;
var foo = "Something";
Console.WriteLine(someReallyLongVariableName);
var c = 'C';
Console.WriteLine(c);

🕹️Basic Data Types:

➡️1. int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647 ➡️ 2. long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

➡️3. float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

➡️4. double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits.

➡️5. bool 1 bit Stores true or false values

➡️6. char 2 bytes Stores a single character/letter, surrounded by single quotes

➡️7. string 2 bytes per character Stores a sequence of characters, surrounded by ➡️ ➡️ double quotes

// Declare some basic value type variables
int i = 10;
float f = 2.5f;
decimal d = 10.0m;
bool b = true; //or false
char c = 'c';
// Declare a string - it's a collection of characters
string str = "this is my name";
// Declare an implicit variable
var x = 10;
var z = "Hello!";
// Declare an array of values
int[] vals = new int[5];
string[] strs = { "one", "two", "three" };

// Print the values using a Formatting String
Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", i, c, b,
str, f, d, x, z);
// "null" means "no value"
object obj = null;
string john = null;
Console.WriteLine(john);
// Implicit conversion between types
long bignum;
bignum = i;
// Explicit conversions
float i_to_f = (float)i;
Console.WriteLine("{0}", i_to_f);
int f_to_i = (int)f;
Console.WriteLine("{0}", f_to_i);

🕹️Operators:

Now that we have some basic types and can create variables, it would sure be nice to have them interact with each other. Operators can be used to interact with our variables. Let’s start by declaring two variables, apples and oranges and interact with them using different operators. Try changing some of the values and tinkering with the operators in the following code snippets.

//Basic arithmetic operators and assignment are available:
var apples = 100m; // Decimal value
var oranges = 30m; // Decimal value
Console.WriteLine(apples + oranges);
Console.WriteLine(apples - oranges);
Console.WriteLine(apples * oranges);
Console.WriteLine((int)apples / 7m);

You can use the equals character = to assign values, and prefix it with an arithmetic operator to modify and assign the resultant value.

var apples = 100m;
Console.WriteLine(apples += 10); //apples = apples + 10
Console.WriteLine(apples -= 10); //apples = apples - 10
Console.WriteLine(apples *= 10); //apples = apples * 10
Console.WriteLine(apples /= 3m); //apples = apples / 3
Console.WriteLine(30.0d == 30);

C# makes the inequality operators available as well, and a test for equality using ==

Console.WriteLine(apples > oranges);  //greator than
Console.WriteLine(apples >= oranges); //greaterthan or equal to
Console.WriteLine(apples < oranges); //less than
Console.WriteLine(apples <= oranges); //less than or equal to
Console.WriteLine(apples == oranges); //equal to
Console.WriteLine(apples != oranges); //The not-equals operator

😎😎 Declare some variables to excercise the operators

int x=10, y=5;
string a="abcd", b="efgh";
// Basic math operators are +, -, /, *
Console.WriteLine("----- Basic Math -----");
Console.WriteLine((x / y) * x);
Console.WriteLine(a + b);
// Increment / decrement operators
Console.WriteLine("----- Shorthand -----");
// x++;
// y--;
Console.WriteLine(x);
Console.WriteLine(y);
// Operators can be shorthand: a = a + b
a += b;
Console.WriteLine(a);
// Logical operators &&, ||
Console.WriteLine("----- Logic Operators -----");
Console.WriteLine(x > y && y >= 5); //true
Console.WriteLine(x < y || y > 5); // false
// null-coalescing operators
string str = null;
// the ?? operator uses left operand if not null, or right one if it
is
Console.WriteLine(str ?? "Unknown string");
// the ??= operator assigns the right operand if the left one is null
// it replaces the code:⬇️
// if (variable is null) {
// variable = somevalue;
// }
str ??= "New string";
Console.WriteLine(str);

🕹️Data Types : Date

Dates are a more complex data type that you can interact with by using the DateTime type. We can assign a new Date and time with a new statement to construct the DateTime type. Complete documentation of the DateTime type is available at docs.microsoft.com

DateTime today = new DateTime(2020, 8, 1, 9, 15, 30); /* Create a 
date for August 1, 2020 at 9:00am */
Console.WriteLine(today);
Console.WriteLine(today.Hour); /* We can reference parts of the DateTime as
properties on the variable */
Console.WriteLine(today.Minute);
Console.WriteLine(today.Second);

There are several properties on the DateTime object that allow us to interact with the variable type itself:

Console.WriteLine(DateTime.Now); // Display the current local time
Console.WriteLine(DateTime.MaxValue); // Display the maximum date value
Console.WriteLine(DateTime.MinValue); // Display the maximum date value

We can also add durations to our date like days and hours. The TimeSpan type is available to define a time duration that we can interact with

Console.WriteLine(today.AddDays(7)); // Add a week to November 1
TimeSpan ThreeHours = TimeSpan.FromHours(3); // Define a TimeSpan of 3 hours
Console.WriteLine(ThreeHours); // Show 3 hours as a string
Console.WriteLine(today.Add(ThreeHours)); // Add 3 hours to 'today' and display the result

🕹️Data Types : Tuples

A Tuple can be used to group together related data elements in a lightweight structure. Use parenthesis with the value-types to combine:

(int, int) point = (24, 35);
Console.WriteLine(point);

You can access the items in the Tuple with the Item# properties of the Tuple instance:

Console.WriteLine(point.Item1);
Console.WriteLine(point.Item2);

Tuples can have names assigned to the properties as well:

(decimal Latitude, decimal Longitude) Philadelphia = (39.95233m, -
75.16379m);
Console.WriteLine(Philadelphia);
Console.WriteLine(Philadelphia.Latitude);
Console.WriteLine(Philadelphia.Longitude);

⭐Program Flow⭐

Are recipes which have a particular start spots and special rules on how the computer follows them. In general, a program will start at some “main” routine and continue “downward” one line at a time until the end of the function is reached

C# supports the usual logical conditions from mathematics:

➡️ Less than: a < b

➡️ Greater than or equal to: a >= b

➡️Equal to a == b

➡️ Not Equal to: a != b

You can use these conditions to perform different actions for different decisions. C# has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed.

  1. IF
  2. IF-ELSE
  3. CONDITIONAL SWITCH
  4. LOOPS ie FOR LOOP, WHILE LOOP, DO WHILE LOOP,FOREACH
  5. BREAK CONTINUE
  6. EXCEPTIONS

🕹️The if Statement

Use the else statement to specify a block of code to be executed if the condition is False.

int time = 110;
if (time < 18) //condition to be checked 🤔🤔
{
Console.WriteLine("Good day."); // block of code to be executed if
the condition is True
}
else
{
Console.WriteLine("Good evening."); // block of code to be executed
if the condition is False
}
// Outputs "Good evening."

🕹️The else if Statement

Use the else if statement to specify a new condition if the first condition is False.

int time = 112;
if (time < 10) //condition to be checked 🤔🤔
{
Console.WriteLine("Good morning."); // block of code to be executed
if the condition IF is True
}
else if (time < 20) //condition to be checked 🤔🤔
{
Console.WriteLine("Good day."); // block of code to be executed if
the condition ELSE IF is True
}
else
{
Console.WriteLine("Good evening."); // block of code to be executed
if all the above conditions are False
}
// Outputs "Good evening."

🕹️The Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}

This is how it works:
⭐The switch expression is evaluated once
⭐The value of the expression is compared with the values of each
case
⭐If there is a match, the associated block of code is executed
⭐The break and default keywords will be described later in this
chapter

The example below uses the weekday number to calculate the weekday name:

int day = 888;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default :
Console.WriteLine("Invalid number of the day");
break;
}
//output⬇️
//Invalid number of the day

🕹️ForLoop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Syntax :
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
⭐ Statement 1 is executed (one time) before the execution of the code
block.
⭐ Statement 2 defines the condition for executing the code block.
⭐ Statement 3 is executed (every time) after the code block has been
executed.
// the basic for loop
int myVal = 15;
Console.WriteLine("The basic for loop:"); /*it will output "The basic for loop:" */
for (int i = 0; i < myVal; i++) {
Console.WriteLine("i is currently {0}", i);
}
//output.⬇️
The basic for loop: 
i is currently 0
i is currently 1
i is currently 2
i is currently 3
i is currently 4
i is currently 5
i is currently 6
i is currently 7
i is currently 8
i is currently 9
i is currently 10
i is currently 11
i is currently 12
i is currently 13
i is currently 14

Double ForLoops

using two forloops to create a rightangled triangle od stars.

//PRINT A TRIANGLE OF STARS
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
//output⬇️
*
**
***
****
*****
******

🕹️The foreach Loop

There is also a foreach loop, which is used exclusively to loop through elements in an array:

//the foreach-in loop can be used to iterate over sequences
int[] nums = new int[] {3, 14, 15, 92, 6};
Console.WriteLine("The foreach loop:");
foreach (int i in nums) {
Console.WriteLine("i is currently {0}", i);
}
/* outputThe foreach loop:
i is currently 3
i is currently 14
i is currently 15
i is currently 92
i is currently 6 */
// count the number of o's in the string
string str = "The quick brown fox jumps over the lazy dog";
var count = 0;
foreach (char c in str) {
if (c == 't') {
count++;
}
}
Console.WriteLine("Counted {0} o characters", count);
//output Counted 1 o characters

🕹️Loops

Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable.

🕹️While Loop:

The while loop loops through a block of code as long as a specified condition is True:

Syntax
while (condition)
{
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
/* output
0
1
2
3
4 */

🕹️The Do-While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax:
do
{
// code block to be executed
}
while (condition);
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
/*0
1
2
3
4 */

🕹️Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch statement.

The break statement can also be used to jump out of a loop. This example jumps out of the loop when i is equal to 4:

for (int i = 0; i < 10; i++)
{
if (i == 9)
{
// Console.WriteLine("Break!!!"); //
break;
}
Console.WriteLine(i);
}
/* output
0
1
2
3
4
5
6
7
8 */

🕹️Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
/* output
0
1
2
3
5
6
7 */

🕹️Break and Continue in While Loop

You can also use break and continue in while loops:

int[] values = {3, 7, 12, 23, 25, 28, 29, 36, 47, 57};
Console.WriteLine("Using break and continue :");
foreach (int val in values)
{
// The continue statement skips the rest of the loop entirely
// and jumps to the next iteration (if there is one)
if (val >= 20 && val <= 29) {
continue;
}
// The break statement stops the loop and exits
if (val >= 40) {
break;
}
Console.WriteLine($"val is currently {val}"); // print the value
}
/* output
Using break and continue :
val is currently 3
val is currently 7
val is currently 12
val is currently 36 */

🕹️Exceptions — Try..Catch

When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).

The try statement allows you to define a block of code to be tested 
for errors while it is being executed.
The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
Syntax:
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
/*Index was outside the bounds of the array. */
// You can also output your own error message:
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
/* output
Something went wrong. */

🕹️Exceptions — Finally

The finally statement lets you execute code, after try…catch, regardless of the result:

try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}
/*output
Something went wrong.
The 'try catch' is finished. */

🕹️The throw keyword

The throw statement allows you to create a custom error. The throw statement is used together with an exception class. There are many exception classes available in C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, etc:

int x = 100;
int y = 0;
int result;
try {
if (x > 1000) {
throw new ArgumentOutOfRangeException("x","x has to be 1000 or
less");
}
result = x / y;
Console.WriteLine("The result is: {0}", result);
}
catch (DivideByZeroException e) {
Console.WriteLine("Whoops!");
Console.WriteLine(e.Message);
}
catch (ArgumentOutOfRangeException e) {
Console.WriteLine("Sorry, 1000 is the limit");
Console.WriteLine(e.Message);
}
finally {
Console.WriteLine("This code always runs.");
}
/* output
Whoops!
his code always runs. */

--

--

Kevin Comba Gatimu

🎇computer science student🎇Microsoft Learn Student Ambassador🎇 MERN stack🎇. Currently learning C#. LinkedIn https://www.linkedin.com/in/kevin-comba-gatimu