Coding Heaven logo

Coding Heaven

C# Basics. First Steps.

    Category: C#
Author's Photo

Author: V.

Date: 09/20/2024

Thumbnail for C# First Steps Article

C# First Steps

Hey there, fellow coder! đź‘‹ Whether you're just starting out or looking to brush up on the basics, you've come to the right place


If you’re more of a visual learner, definitely check out the video! But if you’re cool with reading, just dive in and start going through the post. Either way, you’re in for a fun ride!



Let’s kick off this article by exploring one of the most basic yet fundamental concepts in programming: the variable.
What is a variable? It is a memory piece that stores a value that might change in the future. C# is a strongly-typed programming language, which means that every variable must be declared with a specific data type.
This helps the compiler understand what kind of data the variable will hold, ensuring that operations on the variable are safe and appropriate.

Let’s take a look at the code below and explore our data types.

//Program.cs
 class Program // our main class, entry point of our app
 {  
    // Main method is  where the execution of your program begins.
    // .NET will look for it
    static void Main(string[] args) 
    {
        //Variables and different data types it can store 
        string userName = "Alex";
        int age = 37;
         // general use
        double availableFunds = 4000.50;
         // less memory but lower precision
        float deposit = 500.50f;
        char gender = 'M';
        bool isSingle = true;

        // Reassign a variable
        userName = "John Smith"; // this will work
        userName = 12; // this will NOT work, c# compiler will throw an error

    }

 }


This C# Program.cs is a great starting point for understanding the fundamentals of variables, logic, and loops. Let’s break down the code step-by-step and explain each part in simple terms.

When you declare a variable, you must specify both its name and its type, and C# provides a wide variety of types to choose from. This example shows:

👉 String - is used to store text or sequences of characters. In this case, the variable holds the name “Alex”.

👉 Integer - is used to store whole numbers without decimal points. In this case, the value 37 represents the user’s age.

👉 Double - is used to store decimal numbers with high precision

👉 Float - similar to double but with less precision and a smaller range of values.

👉 Char - char is used to store a single character, like a letter, digit, or symbol.

👉 Boolean - can only have two possible values: true or false. It’s commonly used for conditions, flags, and toggling values.


We have much more data types, but these are the most common ones, and primitives. Let's take a look how to print something in C#:


 Console.WriteLine("We have a new user!");
 // combine variable with a string    
 Console.WriteLine("Username: "  + username); 
 Console.WriteLine("Current user age is:" + age + "\n" + "Available Funds: $"
 + availableFunds);
 //String interpolation
 Console.WriteLine($"Current user marriage status is signle: {isSingle}");

 Console.WriteLine("New Balance is: $" + (deposit + availableFunds));

 // Change our variable value (or reassign)
 // this statement is the same as  availableFunds = availableFunds + deposit;
 availableFunds += deposit; 



If/Else statement

In the world of programming, if/else is like asking yourself, “What should I do if something happens?” It’s a way to set up conditions in your code, so it can make decisions based on what’s happening at that moment.

Imagine you’re creating a simple banking system where a user can withdraw money from their account. The program needs to check:

👉 If the withdrawal amount exceeds the available balance (meaning there’s not enough money).
👉 If the withdrawal amount matches exactly the available balance.
👉 If the withdrawal amount is less than the available funds (allowing the withdrawal).

Here is how C# if/else will look like for this scenario:


  /* Control Flow - If/Else statement*/
 double withdrawalAmount = 7500;

    // We have <, >, <=, >=, == comparison operators
 if(withdrawalAmount >= availableFunds){ 
        Console.WriteLine("Not enough funds!");
 }

 else if(withdrawalAmount == availableFunds){
    availableFunds -= withdrawalAmount; 
    Console.WriteLine("Withdrawing all available funds. Current balance is" 
    + availableFunds);
 }
 else{
        availableFunds = availableFunds - withdrawalAmount; 
        Console.WriteLine("Success! Your current balance is:" + availableFunds);
 }
   

When you have multiple choices to evaluate in your program, it’s easy to get overwhelmed with a bunch of if/else statements. But don't worry—there's a cleaner, more efficient way to handle multiple options. And this is a switch statement

It helps us to check a variable against a list of possible values (called cases) and execute a block of code based on which value the variable matches.


 int option = 2;

 switch(option) {

    case 1:
        Console.WriteLine("Option selected: deposit");
        break;
    case 2:
        Console.WriteLine("Option selected: withdraw");
        break;
    case 3:
        Console.WriteLine("Option selected: display balance");
        break;
    default:
        Console.WriteLine("Invalid option!");
        break;
 }


Logical Operators


Alright, let’s talk about logical operators. These are super handy when you need to check multiple things at once in your program. They help you combine conditions and make decisions based on more than one factor.

C# has 4 logical operators: AND (&&), OR (||), NOT (!), XOR (^)

 // age > 18, funds > 2000 or deposit is 4000 or more

        if(age >= 18 && (availableFunds > 2000 || deposit >= 4000)){
            Console.WriteLine("Eligible for loan!");
        }
        else if (age < 18 && availableFunds > 10000 && !isSingle){
            Console.WriteLine("Eligible for loan!");
        }
        else if(isSingle ^ (availableFunds == 10000)){
            Console.WriteLine("Eligible for loan! Based on single offer!");
        }
        else{
            Console.WriteLine("Not eligible for loan.");
        }


👉 AND - both conditions have to be true for the whole thing to be true. If one condition is false, it all falls apart.
👉 OR - only one of the conditions has to be true for the whole thing to be true. So, if either one is true, it works.
👉 NOT - This just flips the truth. If something is true, NOT makes it false; if it’s false, NOT makes it true.
👉 XOR means “either one condition is true, but not both.”


Loops


Loops are a lifesaver when you need to repeat a task over and over again. Instead of writing the same code multiple times, you can use a loop to automate the repetition. In this article, we’ll look at three different types of loops: do-while, while, and for loops.

So, basically a loop is a way to repeat a block of code multiple times, based on a condition you set.


Do While Loop - it guarantees that the code inside the loop will run at least once.


    int loan = 1000;  // Starting loan amount
    int monthlyPayment = 500;  // Monthly payment amount
    int totalPaymentsNumber = loan / monthlyPayment;  // Number of payments

    do {
        loan -= monthlyPayment;  // Deduct monthly payment
        if (loan < 0) {
            Console.WriteLine($"Congratulations! You paid it off!");  // Loan is paid off
            break;  // Exit the loop once the loan is paid off
        }

        Console.WriteLine("Remaining Balance: " + loan);
        totalPaymentsNumber -= 1;
        Console.WriteLine("Payments Left: " + totalPaymentsNumber);
    } while (loan > 0);  // Keep going as long as loan > 0


While Loop - runs only if the Condition is True

It checks the condition before running the code inside the loop. If the condition is false at the start, the loop won’t run at all.


    int loan = 1000;  // Starting loan amount
    int monthlyPayment = 500;  // Monthly payment amount
    int totalPaymentsNumber = loan / monthlyPayment;  // Number of payments

    while (loan > 0) {  // Continue as long as the loan is greater than zero
        loan -= monthlyPayment;  // Deduct monthly payment
        Console.WriteLine("Remaining Balance: " + loan);
        totalPaymentsNumber -= 1;
        Console.WriteLine("Payments Left: " + totalPaymentsNumber);
    }
    


For Loop - perfect when you know exactly how many times you want to repeat a task. For example, if you’re calculating interest over several months, and you know the exact number of months, the for loop is ideal.


    double initialDeposit = 3200;  // Initial deposit amount
    double interestRate = 4.65 / 12 / 100;  // Monthly interest rate
    int monthNumber = 6;  // Number of months to calculate interest for

    for (int i = 0; i < monthNumber; i++) {  // Repeat for the number of months
        initialDeposit += initialDeposit * interestRate;  // Add interest
        Console.WriteLine($"Current balance: ${initialDeposit:F2}");  // Print balance with 2 decimal places
    }


This marks the end of the first part of our C# Foundations series! In the next article, we’ll dive into exciting topics like methods, arrays, and much more. Stay tuned as we continue to explore the essentials of C# programming to help you build a strong foundation.

Happy coding, and see you in the next article!

Tags: C# Variable If/Else Loops backend