Mastering the Fundamentals: A Comprehensive C# Basics Tutorial

Welcome to our comprehensive C# Basics tutorial! Whether you're a beginner looking to dive into the world of C# programming or someone seeking to solidify their foundation in this powerful language, you've come to the right place.

C# (pronounced as "C sharp") is a versatile and widely-used programming language developed by Microsoft. It offers a robust set of features and is commonly used for building various types of applications, including desktop, web, mobile, and gaming.


In this tutorial, we'll take you on a step-by-step journey through the essentials of C# programming. We'll start from scratch, assuming no prior knowledge of the language, and gradually introduce you to the core concepts, syntax, and best practices that will help you write clean and efficient code.

Whether you're interested in developing desktop applications using Windows Forms or diving into web development with ASP.NET, this tutorial will provide you with a solid understanding of the C# language fundamentals. From variables and data types to control structures, functions, and object-oriented programming principles, we'll cover it all.

Our goal is to equip you with the knowledge and confidence to start building your own C# applications. So, grab your favorite text editor, fire up your development environment, and let's embark on this exciting journey together!

Are you ready? Let's dive into the world of C# programming and unlock its limitless possibilities!

Tutorial

Framework → toolbox with a bunch of tools inside to help you accomplish your job better and faster

.NET framework by Microsoft

The terminal is a command line interface that allows us to call certain commands.

Getting Started and Basic C# 

  • download and install .net framework
  • open vs code
  • install C# extension
  • create a new folder
  • click on terminal → new terminal
  • type in the terminal after file name> dotnet new console
  • some files will appear in the explorer
  • click and open Program.cs
  • you can change by going in view → command palette → search for user settings → user settings
  • Ctrl+Shift+P → generate assets for build and debug → launch.json and tasks.json appear
  • go to launch.json → identify this line "console": "internalConsole” → replace internalConsole with externalTerminal → click Save
  • Go back to Program.cs → Go to Run → Start Debugging
  • The program started and finished after the Hello World was executed

To resolve this add the following line after console.writeline:

Console.ReadKey(); //this says that hey we're going to simply wait for any kind of input from our keyboard before moving ahead

The following is a method called 'Main' and it is an Entry method because it is called when the program starts. The stuff that we put in the curly brackets will run when the program begins.

static void Main(string[] args)
        {
            Console.WriteLine("Hello World!"); // Prints out the string Hello World in our console.
            Console.ReadKey(); // Waits for the user to press any button on the keyboard. 
        }
// This is a method called 'Main'

We write console because we want to access the console and change something about it.

The console here is a class. Think of class as a container with a bunch of stuff inside.

When we write the dot after console, we can access everything there is in the console class.

When we write dot, we get two options of things in the class:

  1. Wrench Icon items → variable or property → things we can change about our console like colour, title or size.
  2. Box Icon items → method or function → commands that we can call in order to have a console do different things such as write out a line of text or wait for the user to type in.

We can use the title property to change the title of the console.

We can use the foreground color property to change the text color of the string of text inside the console.

We can even change the size of the window with the window height property by entering a number. The number indicates the number of lines to be displayed in the console.

This is the way to modify properties in C#.

Now write something that actually makes the console do something. Now we have to write a method or function with the box icon.

Methods are always written with an open parenthesis and closed parenthesis and a semi colon at the end.

Before putting our semi-colon, the particular method wants to know what to write. This is called an argument.

Arguments are values that we give to the method to use. Some methods don’t take any arguments while others take many different ones.

Read line method makes the console read what the user wrote.

Writing \n within a string can separate the string into different lines by creating line breaks. So you won’t have to call the method again and again.

Final Code:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            //change the appearance 
            Console.Title = "Skynet"; // changes the title of console to Skynet
            Console.ForegroundColor = ConsoleColor.Green; // changes the color of text in console
            Console.WindowHeight = 20; // changes the height of the console window to 20 lines 

            //get the conversation going
            Console.WriteLine("Hello, What's your name"); //displays the string in console
            Console.ReadLine(); // console reads the string written above

            Console.WriteLine("My name is RX-9000. \\nI am an AI sentient sent from the future to destroy mankind.\\nWhat is you favorite color?");

            Console.ReadLine();

            Console.ForegroundColor = ConsoleColor.DarkRed; // changes color of last line to dark red

            Console.WriteLine("Cool, mine is destruction!");

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    } 

}

Variables 

Think of variables as containers. They allow us to hold information or data.

We can put stuff inside the container or variable.

At any point during our program, we can open the container and access the information that we earlier stored in the container. We can access the information to either change the existing container or use it do something with.

If we make a program that uses the name of our user, we would use a variable to store the name. Then later we can access this information and display it in the program whenever we want.

Variable can have different types.

The type indicates what type of information we want the variable to hold.

Imagine the variable type as the shape of the container. The circular type of container will only take circular information. The triangular type of container will only take triangular information.

In C#, we work with 4 fundamental types:

  1. Int → Integer → can store a whole number, positive or negative. faster than float, so use this unless you need decimals
  2. Float → can store decimals, both positive and negative. Can hold only 7 digits after decimal point, eg. 6.1738499. If you have to store more, use a ‘double’ which can store up to 16 decimal digits.
  3. String → store text in quotation marks, can store both numbers and text
  4. Bool - boolean → can be true or false, simplest

Syntax for any variable:

type name = value

int myAge = 23;
bool Life = false;
float myBill = 25.99;
string myName = "Karan";

Now, C# allows us to cheat here by replacing the type of variable with a var keyword. It happens when the programmer doesn’t know what the variable is going to be or is just lazy.

var myAge = 23;
var Life = false;
var myBill = 25.99;
var myName = "Karan";

In general, it’s better practice to write the actual type of variable instead of the var keyword. This is called being explicit and it helps us avoid making mistakes.

Let’s code a program where it takes in the name of the user.

  1. Ask the user their name with text
  2. create string variable that takes in the value of name typed in by the user
  3. write back to the user using the variable along with a greeting text

Final code from this example:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What is your name?");
            string userName = Console.ReadLine(); // creates a string variable with a value of user iniput from last line

            Console.WriteLine("Hello " + userName + ", nice to meet you. I hope you're doing well!"); //appends the different strings to form a sentence

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    }
}

Declaring a variable is different from giving the variable a value.

When you are creating a new variable, you declare it by simply writing the type of variable and the name with a semi-colon. We haven’t assigned a value to the variable yet.

The write method used instead of writeline allows the user to input the number on the same line which can be a bit cleaner.

To assign an integer a value which is string, you need to first convert the string to an integer. The user can input any text which might not be an integer.

For this you need to use the Convert class.

Different Int conversions like ToInt16, 32, 64 mean that how much memory they’re going to take up. Standard is 32. When you have to store incredibly large numbers, you choose the highest value.

The following code can take integers but not decimal numbers:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            int num01;
            int num02;

            Console.Write("Input a number: ");
            num01 = Convert.ToInt32(Console.ReadLine()); // converts the string input into an integer

            Console.Write("Input secocnd number: ");
            num02 = Convert.ToInt32(Console.ReadLine()); // converts the second string to integer

            int result = num01 * num02; //multiply two values of int variables defined above

            Console.WriteLine("The result is " + result);

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    }
}

Change variable type to float to allow decimal inputs and if more precision is required change it to double. Following is the code with the changes:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            double num01;
            double num02;

            Console.Write("Input a number: ");
            num01 = Convert.ToDouble(Console.ReadLine()); // converts the string input into a double

            Console.Write("Input secocnd number: ");
            num02 = Convert.ToDouble(Console.ReadLine()); // converts the second string to double

            double result = num01 * num02; //multiply two values of double variables defined above

            Console.WriteLine("The result is " + result);

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    }
}

Challenge: Take an average of three decimal numbers which the user will input and give an accurate output. Following is the code solution:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {   
            // first declare the variables
            double num01; 
            double num02;
            double num03;

            // ask the user to input the variables

            Console.Write("Input the first number: ");
            num01 = Convert.ToDouble(Console.ReadLine()); // convert the variable to double

            Console.Write("Input the Second Number: ");
            num02 = Convert.ToDouble(Console.ReadLine());

            Console.Write("Input the third number: ");
            num03 = Convert.ToDouble(Console.ReadLine());

            // apply the mathematical operators to average 
            //declare another variable with the average operations
            double result = num01 + num02 + num03 / 3;

            // write the output to user with the result variable
            Console.WriteLine("The average of these 3 numbers is = " + result);

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    } 

Conditions

The if statement is used to check for different conditions.

Syntax :

if (answer == "Lord of the rings") //condition inside the parenthesis
{
	Console.Write("Correct Answer"); // if the condition is met
}
else 
{
	Console.Write("Incorrect Answer"); //if the condition is not met
}

Different symbols can be used to create conditions.

  • == means ‘is equal to’
  • ! = means ‘is not equal to’
  • means ‘greater than’ when comparing numbers

  • < means ‘less than’ when comparing numbers
  • = means ‘greater than or equal to’

  • < = means ‘less than or equal to’

Let’s get started with an example using conditions.

Suppose you go to the cinema and you want to buy a ticket. Here’s the code for the same:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            // ask user for input
            Console.WriteLine("Welcome! Tickets are 5$. Please insert cash.");

            //declare variable, assign value and convert to integer
            int cash = Convert.ToInt32(Console.ReadLine());

            //apply conditions for the cash a user puts in 
            if (cash < 5)
            {
                Console.WriteLine("That's not enough money."); // execute corresponding method if the cash is less than ticket price
            }

            else if (cash == 5)
            {
                Console.WriteLine("Here's your ticket. Enjoy the Movie!"); // execute corresponding method if cash is exactly equal to ticket price
            }

            else
            {
                int change = cash - 5;
                Console.WriteLine("Here's your ticket and " + change + " dollars in change. Enjoy the movie!"); // execute corresponding method if cash is more than ticket price and return the change back to the user
            }

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    }
}

Another example:

Imagine we are in a theme park and we want to create a programme that check whether or not people are allowed to go onto a rollercoaster.

We want to determine this based on the age and height of the user.

if statements can be nested inside each other to check for a second condition after the first one is met. But there’s an easier way to do it.

&& means AND →: both conditions should be true to proceed

|| means OR → either one of the conditions can be true to proceed

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            //declare variables
            int age;
            int height;

            //input data from users and convert to integer
            Console.Write("Please enter your age: ");
            age = Convert.ToInt32(Console.ReadLine());

            Console.Write("Please enter your height (cm): ");
            height = Convert.ToInt32(Console.ReadLine());

            // use conditions
            if (age >= 18 && height >= 180) //both conditions need to be met for the method to be executed
            {
                Console.WriteLine("You can enter!");
            }

            if (age >= 18 || height >= 180) //one of the conditions should be true for the method to be executed 
            {
                Console.WriteLine("You can enter!");
            }
            
            else
            {
                Console.WriteLine("You shall not pass!");
            }

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    }
}

Whenever we are dealing with a single variable, that can have many different values, and we want to do something based on the value, that is the perfect example of where a switch statement is really useful.

Instead of writing a chain of IF statements like in the example code below which lets the user select a number from 1 to 5 and then returns a word for the same number, :

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please write a number betweeen 1 and 5: ");

            int num = Convert.ToInt32(Console.ReadLine());

            if (num == 1)
            {
                Console.WriteLine("One");
            }
            else if (num == 2)
            {
                Console.WriteLine("Two");
            }
            else if (num == 3)
            {
                Console.WriteLine("Three");
            }
            else if (num == 4)
            {
                Console.WriteLine("Four");
            }
            else if (num == 5)
            {
                Console.WriteLine("Five");
            }
            else
            {
                Console.WriteLine("I told you to chose between 1 and 5");
            }

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    }
}

Instead, we could use the switch statement which makes the code more comprehensible and clear for someone trying to understand the conditional logic for a single variable. Like this:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please write a number betweeen 1 and 5: ");

            int num = Convert.ToInt32(Console.ReadLine());

            switch (num) // switch statement
            {
                case 1: //multiple cases
                    Console.WriteLine("One");
                    break;
                case 2:
                    Console.WriteLine("Two");
                    break;
                case 3:
                    Console.WriteLine("Three");
                    break;
                case 4:
                    Console.WriteLine("Four");
                    break;
                case 5:
                    Console.WriteLine("Five");
                    break;
                default:
                    Console.WriteLine("default");
                    break;
            }

            Console.ReadKey(); // tells the console to wait for a keyboard action from user to proceed
        }
    }
}

💡 Alt + Shift + Down → shortcut to duplicate multiple lines of code

Challenge: Create a math quiz for users with 5 questions using if statements.

Solution:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            // declare variables
            double num01;
            int num02;
            int num03;
            int num04;
            int num05;

            //take user input

            Console.Write("10 + 2 / 6 = ");
            num01 = Convert.ToDouble(Console.ReadLine());
            // apply conditions
            if (num01 == 10.3)
            {
                Console.WriteLine("Correct");
            }
            else
            {
                Console.WriteLine("Wrong");
            }

            Console.Write("15 * 2 * 3 = ");
            num02 = Convert.ToInt32(Console.ReadLine());

            if (num02 == 90)
            {
                Console.WriteLine("Correct");
            }
            else
            {
                Console.WriteLine("Wrong");
            }

            Console.Write("13 * 3 - 6 + 7 = ");
            num03 = Convert.ToInt32(Console.ReadLine());

            if (num03 == 40)
            {
                Console.WriteLine("Correct");
            }
            else
            {
                Console.WriteLine("Wrong");
            }

            Console.Write("30 / 3 - 5 + 15 = ");
            num04 = Convert.ToInt32(Console.ReadLine());

            if (num04 == 20)
            {
                Console.WriteLine("Correct");
            }
            else
            {
                Console.WriteLine("Wrong");
            }

            Console.Write("25/5 * 5 + 5 - 5 = ");
            num05 = Convert.ToInt32(Console.ReadLine());

            if (num05 == 25)
            {
                Console.WriteLine("Correct");
            }
            else
            {
                Console.WriteLine("Wrong");
            }

            // reveal answers to user 
            double num06 = 10 + 2 / 6;
            Console.WriteLine("First Answer is " + num06);

            double num07 = 15 * 2 * 3;
            Console.WriteLine("Second Answer is " + num07);

            double num08 = 13 * 3 - 6 + 7;
            Console.WriteLine("Third Answer is " + num08);

            double num09 = 30 / 3 - 5 + 15;
            Console.WriteLine("Fourth Answer is " + num09);

            double num10 = 25 / 5 * 5 + 5 - 5;
            Console.WriteLine("Fifth Answer is " + num10);

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Another trial at the same challenge in a different way:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            // declare variables
            double num01;
            int num02;
            int num03;
            int num04;
            int num05;

            //take user input

            Console.Write("10 + 2 / 6 = ");
            num01 = Convert.ToDouble(Console.ReadLine());

            Console.Write("15 * 2 * 3 = ");
            num02 = Convert.ToInt32(Console.ReadLine());

            Console.Write("13 * 3 - 6 + 7 = ");
            num03 = Convert.ToInt32(Console.ReadLine());

            Console.Write("30 / 3 - 5 + 15 = ");
            num04 = Convert.ToInt32(Console.ReadLine());

            Console.Write("25/5 * 5 + 5 - 5 = ");
            num05 = Convert.ToInt32(Console.ReadLine());

            // apply conditions
            if (num01 == 10.3 && num02 == 90 && num03 == 40 && num04 == 20 && num05 == 25)
            {
                Console.WriteLine("All answers are Correct");
            }
            else
            {
                Console.WriteLine("Wrong");
            }

            // reveal answers to user 
            double num06 = 10 + 2 / 6;
            Console.WriteLine("First Answer is " + num06);

            double num07 = 15 * 2 * 3;
            Console.WriteLine("Second Answer is " + num07);

            double num08 = 13 * 3 - 6 + 7;
            Console.WriteLine("Third Answer is " + num08);

            double num09 = 30 / 3 - 5 + 15;
            Console.WriteLine("Fourth Answer is " + num09);

            double num10 = 25 / 5 * 5 + 5 - 5;
            Console.WriteLine("Fifth Answer is " + num10);

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Loops 

Loops allow us to repeat code.

Repeat certain parts of our code.

Take advantage of the computer

2 types of loops: FOR and WHILE

FOR LOOPs

FOR loop → when we want to repeat the code a certain number of times.

Let’s say we want to print numbers 1 through 10, we could write console.write 10 times but that’s cumbersome.

We simple write a FOR loop and tell it to run for 10 iterations.

Good thing about FOR loop → gives a variable that tells us what iteration we’re currently at. We call it i. First time the loop runs, i=0 and it increases from there onwards.

If we want the console to print numbers 1 to 10, we simply start with i+1 where i=0 in the first loop that gives us 1 at the start.

Now we need to tell it how many times the code should repeat. We do this inside the parentheses.

Syntax is a bit weird but you’ll get a hang of it.

First off we should write should happen before the loop starts. We create the i variable and set it to 0.

Add a semi colon → then write the condition that needs to be met for our loop to keep running. In this case we want the loop until i<10 and end with a semicolon.

Then we need to tell the computer what happens after each loop. n our case, after each loop, we want it to increase by 1. Shorthand notation for this is i ++

You can create this VS code by writing each line or using the autocomplete code by hitting Tab on the suggestion: for loop.

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 100; i++) //starts at 1, increments by 1, until 100
            {
                Console.WriteLine(i);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}
using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 100; i > 0; i--) //starts at 100, decrements by 1, until it goes to 1
            {
                Console.WriteLine(i);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

We could add complex math operations like printing all powers of 2:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10; i++)
            {
                double result = Math.Pow(2, i);
                Console.WriteLine(result);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Now we can also allow the user to determine how many numbers we should print.

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How many cool numbers do you want?: ");
            int count = Convert.ToInt32(Console.ReadLine());

            for (int i = 1; i <= count; i++) // we set the condition as the count variable which was entered by the user
            {
                double result = Math.Pow(2, i);
                Console.WriteLine(result);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

WHILE LOOPS

This is used when we want to repeat code for as long as a certain condition is met. Here, we often don’t know beforehand how many times the loop is going to run.

Imagine we’re creating a programme to simulate dice rolls, and we want to see how many attempts it takes to roll a six.

In this case, a while loop is perfect because we can keep repeating the code that rolls the die until we hit a six.

Syntax is similar to an if statement.

while(condition) {} → inside we put the condition that needs to be met in order for a while loop to run.

In our example we want to our loop to keep running as long as the roll variable is not equal to six.

Inside the curly brackets, we can simply roll the die, by setting our roll variable to some number between one and six.

So this will keep repeating until we roll the right number.

💡 This is where we have to be careful with WHILE loops because if we don’t write them correctly, we might accidently put in a condition that will always be true. So, in the above example, if we accidently check if a roll is not equal to 7, our roll will always have a value between 1 and 6. And so this loop will keep running infinitely and crash our programme.


Don’t worry if this happens, it only means that our while loop doesn’t know when to stop.

Let’s begin coding the example we mentioned above using the while loop and random class.

A cool thing about loops is that we can actually make it a tiny bit interactive because initially it prints all the numbers at once, so let’s instead have the user press a key before we continue to the next roll.

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            Random numberGen = new Random(); // random class to generate random numbers. This allows us to create a function  that creates random numbers.

            int roll = 0; // integer that will store what we rolled with default to 0

            int attempts = 0; // used to keep track of how many attempts we've used in order to roll that six with default to 0

            Console.WriteLine("Press enter to roll the die.");

            // now create the while loop
            while (roll != 6) // condition that keep rolling as long as our roll is not equal to six
            {
                Console.ReadKey(); // waits for user to press key before executing the while loop. This will take a key press input from the user each time 

                roll = numberGen.Next(1, 7); // first value is inclusive and , second value is exclusive i.e. not included in the calculation. 7 is exclusive here.

                Console.WriteLine("You rolled: " + roll);
                attempts++; // after each attempt we want to go ahead and increase attempts by one.
            }

            Console.WriteLine("It took you " + attempts + " attempts to roll a six.");

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Challenge: Create a programme that rolls two dies at once. Then check how many attempts it takes before you roll two a kind.

Here you need to create another roll variable. Then change the condition of the while loop so that it will run as long as the two rolls are different. Then, inside the while loop, make sure that you’re assigning random numbers to both roll variables. Finally, print out the number of attempts.

Solution:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            Random numberGen = new Random();

            
            int roll01 = 0;
            int roll02 = 1;
            int attempts = 0;

            Console.WriteLine("Press enter to roll the die.");

            while (roll01 != roll02)
            {
                Console.ReadKey();

                roll01 = numberGen.Next(1, 7);
                roll02 = numberGen.Next(1, 7);
                Console.WriteLine("You rolled: " + roll01);
                Console.WriteLine("You rolled: " + roll02);
                                
                attempts++;
            }

            Console.WriteLine("It took you " + attempts + " attempts to roll doubles");

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Arrays

Work with an entire list of items

Use lists and arrays to store many things in a single variable

When we want to create a list of items

Arrays allow us to store multiple values in a single variable.

Every item in the array is associated with a number or index. The first item always has an index of 0.

We use the index to access an element inside the array.

Arrays get interesting when combined with loops.

Let’s try an example:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] movies = { "Lord of the Rigns", "Fight Club", "Interstellar", "Gladiator", "Ring" };

            // loop through these movies using the for loop

            for (int i = 0; i < movies.Length; i++) //instead of hard coding the number of movies, we can add length property, so that even if in future you decide to add more elements to the array above
            {
                int rank = i + 1;
                Console.WriteLine(rank + "." + movies[i]);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Remember the relationship between the index and the value that we’re trying to access.

Sometimes we don’t know beforehand what we want in our array.

If for example, we want to use it to input their favorite movies, we can’t immediately assign values to the array. Instead, we need to create an empty array first and then populate it one by one.

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            // create an array that can hold four strings
            string[] movies = new string[4];

            // tell the user to input 4 movies
            Console.WriteLine("Type four movies: ");

            // assign a value to each element in the array by using index
            // movies [0] = Console.ReadLine();
            // movies [1] = Console.ReadLine();
            // movies [2] = Console.ReadLine();
            // movies [3] = Console.ReadLine();

            //instead of using the above repetitve method we could use the for loop

            for (int i = 0; i < movies.Length; i++)
            {
                movies[i] = Console.ReadLine();
            }

            // the items input by users will be stored in an array and we can access them 
            // for example if we want to sort them alphabetically and present them back to the user we could use the sort method

            Console.WriteLine("\\nHere they are alphabetically: ");

            Array.Sort(movies); // will sort the array alphabetically if text and in ascending order if input is numbers

            for (int i = 0; i < movies.Length; i++)
            {
                Console.WriteLine(movies[i]);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Biggest disadvantage of array is that arrays have a fixed quantity, so if we don’t know beforehand how many elements to take in from the user, we cannot create the array.

Instead we use the list. to use a list, we need to change the namespace.

namespace → groups of functionality that we can import in order to do different things

currently we have been working in the system namespace

using System;
using System.Collections.Generic; // to access the lists functionality

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> shoppingList = new List<string>(); // creates a new list. syntax is different from array

            // add items to shopping list 
            shoppingList.Add("Dreams");
            shoppingList.Add("Miracles");
            shoppingList.Add("Rainbow");
            shoppingList.Add("Pony");

            for (int i = 0; i < shoppingList.Count; i++) //when working with lists, we use count and length with arrays
            {
                Console.WriteLine(shoppingList[i]);
            }

            //we could've done this with array also but what makes lists so handy is that we can easily remove from them
            shoppingList.Remove("Dreams");
            shoppingList.RemoveAt(1);

            Console.WriteLine("-------------");
            for (int i = 0; i < shoppingList.Count; i++) //when working with lists, we use count and length with arrays
            {
                Console.WriteLine(shoppingList[i]);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Challenge: Create a programme that allows a teacher to input all the students in the class and have their names printed out alphabetically

Start by asking: “How many students are in your class? so that you know how large of an array should you create.

Solution:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            // ask teacher to input number of students
            Console.WriteLine("How many students are there in your class?");

            //declare a variable and assign it the input value
            int studentNum = Convert.ToInt32(Console.ReadLine());

            // create an array that can hold this number

            string[] students = new string[studentNum];

            //tell the teacher to input their names
            Console.WriteLine("\\nPlease write their names: ");

            //assign a value to each input name by using index
            for (int i = 0; i < students.Length; i++)
            {
                students[i] = Console.ReadLine();
            }

            // output them alphabetically
            Console.WriteLine("\\nHere they are alphabetically: ");

            //sort them 
            Array.Sort(students);

            // create a for loop to show them to user

            for (int i = 0; i < students.Length; i++)
            {
                Console.WriteLine(students[i]);
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
    }
}

Methods 

A method allows us to group together code that performs a specific task. This way we can write the code only once and then use it whenever we need.

Say we want code that prints a random number in our console. We can create a method that does this.

First we define the method.

Source: Brackey's


Then we call our defined method. Calling a method means telling the code inside to execute.

Source: Brackey's


If we run our programme now, it’s going to see that we want to call the PrintNumber method → go inside of that method → execute all the code inside → result is that we get a random number

We can choose to call this anywhere and as many times as we like.

Source: Brackey's


Methods are also often referred to as functions in C#.

Create a speed dating programme where the user gets to meet a bunch of new people. But, instead of meeting other humans, let’s have the user meets aliens instead.

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            MeetAlien(); // call our method

            Console.WriteLine("-----------");
            MeetAlien(); // call method once again

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }

        static void MeetAlien()
        {
            Random numberGen = new Random();

            string name = "X- " + numberGen.Next(10, 9999);
            int age = numberGen.Next(10, 500);

            Console.WriteLine("Hi, I'm " + name);
            Console.WriteLine("I'm " + age + " years old");
            Console.WriteLine("Oh, and I'm an alien");

        }
    }
}

Methods really start to shine when we add parameters and return values.

Create a method that squares a number.

Input a number that the machine should then square.

Source: Brackey's

void → means we don’t want to return anything

replace it with variable type and you get a return value

Source: Brackey's

Let’s see this example in VS code:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            int answer = Multiply(3, 9);

            Console.WriteLine("The result is: " + answer);

            if (answer % 2 == 0) // modulo operator to check for remainder when dividing with 2. if 0 then even, if not then odd.
            {
                Console.WriteLine(answer + " is an even number");
            }
            else
            {
                Console.WriteLine(answer + " is an odd number");
            }

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }

        static int Multiply(int num01, int num02)
        {
            int result = num01 * num02;
            return result;
        }

    }
}

Challenge: Create a method that can count the number of words in a sentence.

To do this, the method must take in a string, the sentence. Figure out how many words are in that sentence and return that number as an integer.

We need to know how to get the word count. We can do this using the dot split method.

One string can be divided into an array of strings using variableName.Split(’character where you want the split’).Length;

.Length can be used to get the number of elements inside the array

Solution:

using System;

namespace My_Awesome_Program
{
    class Program
    {
        static void Main(string[] args)
        {
            // ask user for input
            Console.WriteLine("Please write your sentence");

            //declare string variable and assign the input value
            string sentence = Console.ReadLine();

            // call the method and give it a variable to be used later
            int wordCount = CountWords(sentence);

            //display output to user
            Console.WriteLine("This sentence has " + wordCount + " words.");

            Console.ReadKey(); // wait for a keyboard action from user to proceed
        }
        
        //define method with parameter and return value
        static int CountWords(string sentence)
        {
            //use dot split method to split the sentence at space and extract the length
            int wordCount = sentence.Split(' ').Length;
            return wordCount; // return the value 
        }

    }
}

Conclusion

Congratulations on completing our comprehensive C# Basics tutorial! You have come a long way from being a beginner to now having a solid foundation in the C# programming language. We hope this tutorial has provided you with the knowledge and skills necessary to embark on your journey as a C# developer.

Throughout this tutorial, we covered essential topics such as variables, data types, control structures, functions, and object-oriented programming. By understanding these core concepts, you now have the tools to write efficient and maintainable code.

Remember, learning programming is a continuous process. It's essential to practice what you have learned and explore further to deepen your understanding of C#. Continue building projects, experimenting with new concepts, and challenging yourself to solve problems. The more you code, the more confident and skilled you will become.

As you progress in your C# journey, consider exploring advanced topics such as LINQ, asynchronous programming, databases, and web development with frameworks like ASP.NET. These areas will open up new possibilities and allow you to build more complex and sophisticated applications.

Additionally, stay engaged with the vibrant C# community. Join online forums, participate in coding communities, and follow industry blogs to stay updated with the latest trends and best practices in C# development. Learning from others and sharing your knowledge will contribute to your growth as a developer.

We hope this tutorial has ignited your passion for C# programming and provided a strong foundation for your future endeavors. Remember, programming is both an art and a science and with dedication and perseverance, you can achieve great things.

Thank you for joining us on this exciting journey into the world of C# programming. Best of luck as you apply your newfound knowledge and skills to build amazing applications. Happy coding!


Popular Posts

Perform CRUD (Create, Read, Update, Delete) Operations using PHP, MySQL and MAMP : Part 4. My First Angular-15 Ionic-7 App

Visualize Your Data: Showcasing Interactive Charts for Numerical Data using Charts JS Library (Part 23) in Your Angular-15 Ionic-7 App

How to Build a Unit Converter for Your Baking Needs with HTML, CSS & Vanilla JavaScript