Basics of C# Programming

Welcome to the basics of C# programming! This section will guide you through the fundamental concepts and syntax of C#. Whether you're new to programming or transitioning from another language, these lessons will help you build a strong foundation.

Getting Started with C#

Introduction to C#

C# is a modern, object-oriented programming language developed by Microsoft. It's widely used for developing Windows applications, web applications, and games using Unity.

Note: C# is part of the .NET framework, which provides a comprehensive set of libraries and tools for building applications.

Your First C# Program

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

Exercise 1.1

Modify the Hello World program to print your name and the current date.

2. Variables and Data Types

C# is a strongly-typed language, which means you must declare the type of data a variable will hold. This helps catch errors at compile-time and makes your code more reliable.

Basic Data Types

// Integer types
int age = 25;                    // 32-bit integer
long bigNumber = 123456789L;     // 64-bit integer

// Floating-point types
float price = 19.99f;            // 32-bit floating point
double pi = 3.14159;             // 64-bit floating point

// Boolean
bool isActive = true;            // true or false

// Character and String
char grade = 'A';                // Single character
string name = "John Doe";        // Text

// DateTime
DateTime today = DateTime.Now;   // Current date and time
Best Practice: Always use meaningful variable names that describe their purpose.

Exercise 2.1

Create variables to store your personal information (name, age, height, etc.) and print them to the console.

3. Control Structures

Control structures help you control the flow of your program. They allow you to make decisions and repeat code blocks based on conditions.

If-Else Statements

int age = 18;

if (age >= 18)
{
    Console.WriteLine("You are an adult");
}
else if (age >= 13)
{
    Console.WriteLine("You are a teenager");
}
else
{
    Console.WriteLine("You are a child");
}

Loops

// For loop
for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"Count: {i}");
}

// While loop
int count = 0;
while (count < 5)
{
    Console.WriteLine($"Count: {count}");
    count++;
}

// Do-while loop
int number = 0;
do
{
    Console.WriteLine($"Number: {number}");
    number++;
} while (number < 5);

Exercise 3.1

Write a program that prints the multiplication table for a number entered by the user.

4. Methods and Functions

Methods are blocks of code that perform specific tasks and can be reused throughout your program. They help organize your code and make it more maintainable.

// Method with no parameters and no return value
void Greet()
{
    Console.WriteLine("Hello!");
}

// Method with parameters and return value
int Add(int a, int b)
{
    return a + b;
}

// Method with optional parameters
void PrintMessage(string message = "Hello, World!")
{
    Console.WriteLine(message);
}

// Method with multiple parameters
void PrintUserInfo(string name, int age, string city = "Unknown")
{
    Console.WriteLine($"Name: {name}");
    Console.WriteLine($"Age: {age}");
    Console.WriteLine($"City: {city}");
}
Best Practice: Keep methods small and focused on a single task. This makes them easier to understand and maintain.

Exercise 4.1

Create a calculator program with methods for basic arithmetic operations (add, subtract, multiply, divide).

5. Arrays and Collections

C# provides several ways to store and manage collections of data. Understanding these data structures is crucial for effective programming.

// Arrays
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };

// Lists
List names = new List();
names.Add("John");
names.Add("Jane");

// Dictionaries
Dictionary ages = new Dictionary();
ages["John"] = 25;
ages["Jane"] = 30;

// Working with collections
foreach (var number in numbers)
{
    Console.WriteLine(number);
}

// LINQ with collections
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Warning: Be careful with array indices. Accessing an index outside the array bounds will throw an exception.

Exercise 5.1

Create a program that manages a list of students and their grades. Include methods to add students, calculate average grades, and find the highest/lowest grades.

Final Project

Create a simple console application that combines all the concepts learned in this section. The application should:

  • Use different data types and variables
  • Implement control structures
  • Include methods with parameters and return values
  • Use arrays or collections to store data
  • Handle user input and display formatted output