Learn C# from scratch for absolute beginners!

Learn C# from scratch for absolute beginners!

Learn the basics of C# and .NET framework

Before reading this article ...

In this tutorial, we will look at several essential C# concepts that you need to know to start programming in C# and the .NET framework. We will see some of the basics of the C# language such as data types and variables, for and while loops, arrays, methods... In the next articles, we will see other advanced concepts about the C# language, object-oriented programming and design patterns in general.

To get the most out of this tutorial, I highly recommend you practice and try to create your own code. If you get stuck on something, you can ask me in the comments section or contact me via DM. Otherwise, you can use other websites.

If you don't know me, my name is Hamza, I am a C# and ML software engineer. If you want to start developing software and learn ML, as a software engineer, I will guide you in this adventure and give you tips every day, follow me and subscribe to my newsletter to receive my daily articles.

Pre-requisites :

To follow along with this article, you only have to have visual studio installed or any compiler you'd like to use, you can use online editors such as: Online C# Compiler (Editor) (programiz.com)
This article is intended for C# beginners, but you can still follow along if you have some knowledge of the language.

Introduction

In this section, we will take a simple c# code example and try to understand some of its components, note that it's okay if you don't understand something for now (such as classes, namespaces, libraries, modifiers, methods ...), we will talk about all these concepts in detail later. But for now, let's go through the following code:

using System; 
namespace Course01
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");
        }
    }
}

When we run this code, we get: Hello world!

Now, let's explore some of its components, Using is a keyword for including libraries like System. The System library is defined as follows : (The definition is taken from learn.microsoft.com website) :

Contains fundamental classes and base classes that define commonly used reference data types and values, event and event handlers, interfaces, attributes, and processing exceptions.

Then for the keyword namespace, it can be defined as a container for classes. We can group a specific type of class to a given namespace. For example, the class Teacher, Student, and Course can be grouped into one namespace called University.

namespace University
{
    class Teacher
    {
    }
    class Course
    {
    }
}

Data Types & Variables :

Variables in c# or any other programming language are like variables in mathematics, they are symbolic representations of numbers or any datatypes, and variables store the value of the specific datatype**.** To declare a variable in C# we use the keyword var : var myVar = 5; The keyword var allows the variable to be of any type (double, int, string...). Let's take an example :

static void Main(string[] args)
{
    var a = "Hello world";
    var b = 5;
    Console.WriteLine($"{a} {b}");
    Console.Read();
}

To create a variable of type integer, we use the keyword int: int a = 5; there are multiple types of integers including int16, int32 and int64. Then, to create a variable of type decimal, the most common way is to use the data type double for example double a = 5.25; we can also use float and decimal ( if you want to use float you should add F at the end of the value : float a = 2.25F; or m for decimal ).

Decimal has a very high accuracy compared to double and float. Double is the most used. Float is not used that often in C#.

Let's take some examples of variables declaration :

int a = 200;
double b = 56.25;
decimal val = 10.80m;
float r = 15.2f;
char c = 'C';
bool isValid = true;
string firstName = "John"

C# Reserved keywords

C# contains reserved words that have special meanings for the compiler. These reserved words are called "keywords". Keywords cannot be used as an identifier (name of a variable, class, interface, etc.).

Here are some of the reserved keywords (Not an exhaustive list): if, else, switch, case, do, for, foreach, in, while, break, continue, default, go, to, return, yield, throw, try, catch, finally, checked, unchecked, fixed, lock.

C# Conditions, If Statements and switch

The C# language is like other languages supports the mathematical conditions :

  • 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

We use the if statement to specify that a block of code is executed if the condition inside the if statement is true.

if (condition) 
{
  // The block of code to be executed if the condition is true.
}

Let's take an example :

if(2 > 1)
{
    Console.WriteLine("Hello world");
}

Since 2 > 1 is true, the code inside the brackets will be executed and we will get "Hello world" printed on the command line.

Now, if the condition is false, we use the else statement to specify the code that will be executed.

if (20 < 18) 
{
  Console.WriteLine("First");
} 
else 
{
  Console.WriteLine("Second");
}
// Output : Second

Now, let's have a look at shorthand if and else statements.

string res = (6 < 18) ? "First" : "Second";
Console.WriteLine(res);

Now, let's have a look at the switch statement.

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

Now, let's take an example to understand more the use of switch statements :

int day = 1;
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;
}

Here, since the day variable is equal to 1, then the result of the previous program will output : Monday. The break keyword is used to tell the program to break out of the switch statement. The default keyword is used to declare a code to be executed if there is no match case.

for, foreach, and while loops

Loops are used to execute a code as long as a given condition is not reached yet. While loops are used to execute a code as long as a condition is true. The syntax of the while loop is the following :

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

Let's take a simple example :

int i = 0;
while (i < 10) 
{
  Console.WriteLine(i);
  i++;
}

In the previous code, the program will print the numbers from 0 to 9.

We have also another variant of while loops, which is the do/while loop that executes a block of code as long as the condition is true.

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

Now, let's have a look on the for loop.
The syntax of the for loop is as follows :

for (stat1; stat2; stat3) 
{
  // the code to be executed
}

Where :

Stat1 is executed (one time) before the execution of the code block.

Stat2 defines the condition for executing the code block.

Stat3 is executed (every time) after the code block has been executed.

For example :

for (int i = 0; i < 3; i++) 
{
  Console.WriteLine(i);
}

C# arrays

Now, let's talk about arrays in C#. Arrays are used to store multiple values in a single variable instead of using multiple variables for each value. For example, let's imagine that a school has 10 teachers : Liam, Oliver, Noah, Emma, Mohammad, Sophia, Harper, William. To store all these names, we can use 10 variables and store each one in a variable, however, we can store them in a single array as follows :

string[] teachers = {"Liam", "Oliver", "Noah", "Emma", "Mohammad", "Sophia", "Harper", "William"};

Of course, we can declare an array of any type (int, char, double ...). Now, to access a given value, we can use array[i] where the first element is indexed as 0. To get the length of the array we can use array.Length

Now, let's create a two-dimensional array :

int[,] numbers = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1} };

To access elements of the two-dimensional arrays, we use the following syntax: arr[i,j]. In the same manner, if we want to change a specific element of the array, we use arr[i,j] = value.

Now, let's see how we can loop through an array :

// Create a two-dimensional array of integers 
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

// Loop through the rows
for (int i = 0; i < numbers.GetLength(0); i++) 
{ 
      // Loop through the columns
      for (int j = 0; j < numbers.GetLength(1); j++) 
      { 
          // Print the values
          Console.WriteLine(numbers[i, j]); 
      } 
}

Let's have a break!

Now, before moving any further, let's practice all that we have seen until now. For that, let's create an array of prices, and print only the prices greater that a specific value given by the user :

using System;
namespace CsharpEssentials
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Let's ask the user to enter the price threshold
            Console.WriteLine("Enter the threshold :");
            // Let's get the value from the command line
            string priceThreshStr = Console.ReadLine();
            // Let's convert the price from string to double
            double priceThresh = Convert.ToDouble(priceThreshStr);

            // Now, let's create the array of prices
            double[] prices = { 44.5, 55.6, 99.99, 22, 12.99, 5.99 };

            // Now, let's use a for loop over the array values
            for(int i = 0; i < prices.Length; i++)
            {
                // Now, let's check if array elements are greater than the price threshold specified by the user.
                if(prices[i] > priceThresh)
                {
                    // If the previous condition is true then let's print the following message in the command line
                    Console.WriteLine($"Price {i} is : {prices[i]}");
                }
            }

            // Now, let's use the following command to keep the command line until the user hit enters.
            Console.WriteLine("Hit any button to quit the program!");
            Console.ReadLine();
        }
    }
}

C# Methods

If you are coming from another programming language, you must have used methods (aka functions). If not, methods contain a block of code that is only run when the method is called. Methods can take data known as parameters. Methods can also return some data.

A method is defined by it name followed by the parenthesis (). Let's create a method to see how it's done :

class CsharpEssentials
{
  static void MyMethod() 
  {
    // The block of code to be executed
  }
}

Example Explained

  • MyMethod() is the name of the method

  • static means that the method belongs to the Program class and not an object of the Program class. You will learn more about objects and how to access methods through objects later in this tutorial.

  • void means that this method does not have a return value. You will learn more about return values later in this chapter

Now, let's call a method, for that we must write the method's name followed by two parentheses () and a semicolon**;**

static void SayHello() 
{
  Console.WriteLine("Hello !");
}

static void Main(string[] args)
{
  SayHello();
}

// Outputs "Hello"

Now, let's create a function that takes some data as parameters which are specified inside the parenthesis.

For example, let's create a function called SayHello that takes a name of type string as parameter and prints Hello + name.

using System;
namespace CsharpEssentials
{
    internal class Program
    {
        static void SayHello(string name)
        {
            Console.WriteLine("Hello " + name);
        }
        static void Main(string[] args)
        {
            SayHello("James");
            Console.ReadLine();
        }
    }
}

What Next?...

In the next tutorials we will see more concepts about C# including :

  • Some advanced C# concepts

  • Classes and object-oriented programming.

  • The library System.Linq

  • More about C# arrays and lists

  • How to create WPF and windows forms applications

  • Databases and SQL

  • Asynchronous programming in C#

  • Design patterns principles

Finally ...

Thank you for reading this article! If you find it useful, be sure to leave a comment and subscribe to receive more articles like this one.

Did you find this article valuable?

Support Interrupt101 by becoming a sponsor. Any amount is appreciated!