C# Fundamentals

Welcome to the C# Fundamentals tutorial. This guide will walk you through the essential concepts of the C# programming language, designed for beginners and those looking to refresh their knowledge.

Introduction to C#

C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft. It's widely used for developing a variety of applications, including Windows desktop apps, web applications, mobile apps (with Xamarin), games (with Unity), and more. C# is a type-safe language that runs on the .NET platform.

Your First C# Program: "Hello, World!"

Let's start with a simple "Hello, World!" program. This is a traditional first step in learning any new programming language.

Program.cs

using System;

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

Explanation:

Variables and Data Types

Variables are containers for storing data values. C# is statically typed, meaning you must declare the type of a variable before using it.

Common Data Types:

Variables Example

int age = 30;
double price = 19.99;
char initial = 'J';
string name = "Jane Doe";
bool isActive = true;

Console.WriteLine($"Name: {name}, Age: {age}");

Operators

Operators are used to perform operations on variables and values.

Arithmetic Operators:

Assignment Operators:

Comparison Operators:

Control Flow Statements

Control flow statements allow you to execute different blocks of code based on certain conditions.

if-else Statements:

If-Else Example

int number = 15;

if (number > 10)
{
    Console.WriteLine("The number is greater than 10.");
}
else if (number == 10)
{
    Console.WriteLine("The number is exactly 10.");
}
else
{
    Console.WriteLine("The number is less than 10.");
}

switch Statement:

Switch Example

char grade = 'B';

switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent!");
        break;
    case 'B':
        Console.WriteLine("Good job!");
        break;
    case 'C':
        Console.WriteLine("Satisfactory.");
        break;
    default:
        Console.WriteLine("Needs improvement.");
        break;
}

Loops

Loops are used to execute a block of code repeatedly.

for Loop:

For Loop Example

for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"Iteration number: {i}");
}

while Loop:

While Loop Example

int count = 0;
while (count < 3)
{
    Console.WriteLine($"Count is: {count}");
    count++;
}

foreach Loop:

The foreach loop is typically used to iterate over collections like arrays.

ForEach Loop Example

string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

Next Steps

This tutorial covers the very basics. To continue your C# journey, explore topics such as: