🚀C# Foundations

Build essential groundwork in C#. Learn core syntax, variables, control flow, and program structure to confidently write basic C# applications.

👋 Hello, C# World

Welcome to C#! This section will guide you through writing, compiling, and running your first C# program. We'll cover the essentials of C# syntax, project structure, and development tools.

💡 What is C#?

  • C# is a modern, object-oriented programming language developed by Microsoft
  • Runs on the .NET platform and cross-platform with .NET Core/SDK
  • Popular for desktop applications, web services, gaming (Unity), and more

Getting Started - Your First Program

// Example.cs
using System;

namespace HelloWorld {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Hello, C# World!");
        }
    }
}

Let's break down the components of this program: - using System - Accesses core .NET functionality - namespace HelloWorld - Organizes code logically - class Program - Contains the application logic - Main() method - Entry point of the program

💡 Compiling and Running

  • Use .NET SDK command: dotnet run to build and execute
  • Or use an IDE like Visual Studio or Rider for debugging
  • Output will be displayed in the console

Understanding Project Structure

A typical C# project includes: - Program.cs - Main entry file - Project file (e.g., .csproj) - Build configuration - bin/obj folders - Compiled output

💡 Namespaces and Organizing Code

  • Namespaces group related classes together
  • Use using directives to reference namespaces
  • Create your own namespaces for logical organization

Hello World Variations

// Multiple messages
Console.WriteLine("Hello, C# World!");
Console.WriteLine("Exploring the fundamentals.");

// Using variables
string message = "Welcome to C#!";
Console.WriteLine(message);

💡 Best Practices for Console Apps

  • Keep Main() simple and focused on execution flow
  • Move complex logic to separate classes/methods
  • Use meaningful variable names (e.g., message instead of m)
  • Avoid excessive output - use logging for debugging

Common Mistakes to Avoid

  • Don't forget the ; at the end of statements
  • Avoid using single-letter variable names except for loops
  • Don't nest too many conditionals - break into methods
  • Always ensure proper error handling

Real-World Example

using System;

namespace CommandLineTool {
    class Program {
        static void Main(string[] args) {
            if (args.Length == 0) {
                Console.WriteLine("Please provide a command.");
                return;
            }

            string command = args[0].ToLower();
            switch(command) {
                case "help":
                    ShowHelp();
                    break;
                case "version":
                    DisplayVersion();
                    break;
                default:
                    Console.WriteLine($"Unknown command: {command}");
                    break;
            }
        }

        private static void ShowHelp() {
            Console.WriteLine("Available commands:");
            Console.WriteLine("- help: Displays this message");
            Console.WriteLine("- version: Shows the current version");
        }

        private static void DisplayVersion() {
            Console.WriteLine("Version 1.0.0");
        }
    }
}

This example demonstrates: - Command line argument handling - Method organization - Error checking and help functionality

💡 Debugging Tips

  • Use Console.WriteLine for debugging output
  • Run the program in debug mode (F5 in VS)
  • Set breakpoints to pause execution at specific points
  • Inspect variable values during debugging

📦 Data Types and Variables

Welcome to Data Types and Variables! This chapter will guide you through the core concepts of C# data handling, including value vs. reference types, type inference with `var`, and nullable types.

💡 Variables in C#

Variables are containers for storing data values. In C#, variables can be declared using specific data types, which determine their size and behavior.

💡 Value vs. Reference Types

C# has two main categories of data types: value types and reference types.

  • Value Types store the value directly in memory (e.g., `int`, `double`, `bool`). Changes to the variable affect only that instance.
  • Reference Types store a reference to an object's location in memory (e.g., `string`, `object`, arrays). Multiple variables can reference the same object.
// Value type example
int number = 10;

// Reference type example
string name = "Alice";

💡 Type Inference with `var`

The `var` keyword allows the compiler to infer the variable's type based on its initial assignment. Use it for clarity when the type is obvious.

// Explicit declaration
List<string> myList = new List<string>();

// Type inference with var
var myList = new List<string>();

💡 Nullable Types

Nullable types allow variables to hold their type's value or `null`. Use the `?` modifier after a value type.

// Nullable int
decimal? price = 29.99m;

// Check for null
if (price is not null)
{
    Console.WriteLine(price.Value);
}

💡 Constants and Best Practices

Use `const` for values that never change. Avoid unnecessary boxing/unboxing by choosing appropriate value types.

  • Use `var` only when the type is clear and unambiguous.
  • Avoid using nullable types unless necessary to avoid null reference exceptions.
  • Always initialize variables before use.
  • Prefer immutable data structures for thread safety.

🧭 Control Flow and Logic

💡 Introduction to Control Flow

Control flow determines the order in which operations are performed. It's essential for creating dynamic and responsive applications. In C#, we use conditional statements, switch statements, and various loops to control program flow.

💡 Conditional Statements

The most basic form of conditional logic is the if statement. It allows you to execute code blocks based on whether a condition evaluates to true or false.

int temperature = 25;
if (temperature > 30)
{
    Console.WriteLine("It's hot outside!");
}
else if (temperature < 15)
{
    Console.WriteLine("It's cold outside!");
}
else
{
    Console.WriteLine("The weather is pleasant.");
}

Switch Statements

Use the switch statement when you have multiple conditional branches based on a single value. It's more readable than long chains of if-else statements.

string day = "Monday";
switch (day)
{
    case "Monday":
        Console.WriteLine("Start of the workweek!");
        break;
    case "Friday":
        Console.WriteLine("End of the workweek!");
        break;
    default:
        Console.WriteLine("Weekend or holiday.");
        break;
}

💡 Loops in C#

C# provides several loop constructs to repeat operations: 1. for loops - When you know how many times a loop will execute 2. while loops - When you want to check the condition before each iteration 3. do-while loops - When you want to execute at least one iteration regardless of the condition 4. foreach loops - For iterating over collections

// for loop
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

// while loop
int j = 0;
while (j < 5)
{
    Console.WriteLine(j);
    j++;
}
// do-while loop
date j = 0;
do
{
    Console.WriteLine(j);
    j++;
} while (j < 5);
// foreach loop
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

Best Practices for Control Flow

  • Use meaningful variable names for loop counters and condition checks.
  • Avoid deep nesting by restructuring code when possible.
  • Prefer foreach loops over manual index management for collections.
  • Use switch expressions (C# 8+) for concise conditional logic.

Common Mistakes to Avoid

  • Don't use single-line if statements without braces (e.g., `if(x==5) doSomething();`) as it can lead to bugs.
  • Avoid infinite loops by ensuring exit conditions are properly implemented.
  • Be cautious of off-by-one errors when working with loop counters and array indices.

💡 Real-World Application

Control flow is used in almost every part of an application. For example, user authentication systems use conditionals to check credentials, while data processing pipelines use loops and switch statements to handle different types of input.

Quiz

Question 1 of 14

What is the entry point of a C# console application?

  • Start()
  • Main()
  • Run()
  • Execute()