Back-end · formation gratuite

C# Training

Learn C#, a modern and powerful programming language

  • Intermédiaire
  • 13 chapitres
  • Exemples de code
  • 100 % gratuit
Commencer le cours

Introduction to C#

C# is a modern object-oriented programming language developed by Microsoft in 2000. C# is part of the .NET platform and is used to develop Windows, web, mobile, and cloud applications.

⚙️ What is C#?

C# is a object-oriented, type-safe, and managed programming language. C# is compiled to bytecode that runs on the .NET virtual machine (CLR).

💡 Why is C# so important?

  1. .NET ecosystem - Access to a vast library of frameworks and tools
  2. Cross-platform - .NET Core enables cross-platform development
  3. Productivity - Modern syntax and advanced features (LINQ, async/await)
  4. Industry - Widely used in enterprise application development
  5. Unity - Primary language for game development with Unity
  6. Microsoft - Actively supported and developed by Microsoft

🚀 Why learn C#?

C# is a modern and versatile language that offers many professional opportunities. Here's why you should learn C#:

  • ✅ Windows applications - Development of modern desktop applications
  • ✅ Web development - ASP.NET Core for high-performance web applications
  • ✅ Video games - Unity uses C# as the primary language
  • ✅ Mobile - Xamarin enables cross-platform mobile development
  • ✅ Cloud - Azure and Microsoft cloud services
  • ✅ Career - Highly sought after in the industry, especially for enterprise applications

📋 Prerequisites to learn C#

To learn C# effectively, it is recommended to have a foundation in programming (variables, conditions, loops).

  • ✅ Programming basics - Understanding basic concepts (variables, conditions, loops)
  • ✅ Object-oriented programming (optional) - Having OOP basics facilitates learning
  • ✅ Visual Studio or VS Code - Recommended IDE for C# development

💡 Important note: To compile C# code, you need .NET SDK. Download it from the official Microsoft website. Visual Studio Code with the C# extension is also an excellent option.

🎯 C# Use Cases

C# is used in many domains:

  • 🖥️ Windows applications - Desktop application development
  • 🌐 Web development - ASP.NET Core for web applications
  • 🎮 Video games - Unity uses C# as the primary language
  • 📱 Mobile - Xamarin for cross-platform applications
  • ☁️ Cloud - Azure and Microsoft cloud services
  • 💼 Enterprise applications - Robust enterprise solutions
  • 🔧 APIs and services - REST API development
  • 🤖 Machine Learning - ML.NET for machine learning

📝 Basic Syntax

C# is an object-oriented programming language. C# uses braces {} to define code blocks and requires a semicolon ; at the end of each statement.

// Premier programme C#
using System;

class Program {
    static void Main() {
        Console.WriteLine("Bonjour, monde !");
        
        // Variables
        int age = 25;
        string nom = "NiangProgrammeur";
        
        // Affichage formaté
        Console.WriteLine($"Je m'appelle {nom} et j'ai {age} ans");
        
        // Opérations simples
        int resultat = 10 + 5;
        Console.WriteLine($"10 + 5 = {resultat}");
    }
}

💡 Important points about C# syntax:

  • C# uses braces {} to define code blocks
  • Comments use // for a single line or /* */ for multiple lines
  • Semicolon required ; at the end of each statement
  • Strings use double quotes "
  • Each C# program has a class with a Main() method
  • Class names start with a capital letter (PascalCase convention)

🔍 Detailed syntax example

Here is a complete example showing several aspects of C# syntax:

using System;

// Définition d'une méthode
static double CalculerMoyenne(int[] nombres) {
    if (nombres.Length == 0) {
        return 0;
    }
    int somme = 0;
    foreach (int n in nombres) {
        somme += n;
    }
    return (double)somme / nombres.Length;
}

// Méthode principale
class Program {
    static void Main() {
        int[] notes = {15, 18, 12, 20, 16};
        double moyenne = CalculerMoyenne(notes);
        Console.WriteLine($"La moyenne est : {moyenne}");
    }
}

🔤 Variables

In C#, variables can be declared with an explicit type or with var (type inference). C# is a statically typed language.

using System;

class Program {
    static void Main() {
        // Déclaration de variables
        int age = 30;                    // Entier
        float prix = 19.99f;             // Nombre décimal (simple précision)
        double decimalValue = 3.14159;   // Nombre décimal (double précision)
        char lettre = 'A';               // Caractère unique
        string nom = "C#";                // Chaîne de caractères
        
        // Affichage avec Console.WriteLine
        Console.WriteLine($"Age: {age}");
        Console.WriteLine($"Prix: {prix:F2}");
        Console.WriteLine($"Decimal: {decimalValue}");
        Console.WriteLine($"Lettre: {lettre}");
        Console.WriteLine($"Nom: {nom}");
        
        // Déclaration puis assignation
        int nombre;
        nombre = 10;
        Console.WriteLine($"Nombre: {nombre}");
        
        // Constantes avec const
        const double PI = 3.14159;
        const int MAX_SIZE = 100;
        const int TAILLE = 50;
        const string MESSAGE = "Bonjour";
        
        // Noms de variables valides
        int ageUtilisateur = 25;
        string nomUtilisateur = "Bassirou";
        float _prive = 3.14f;  // Possible mais non recommandé
        
        // Inférence de type avec var
        var nombre2 = 42;
        var texte = "Hello";
    }
}

📌 Rules for variable names:

  • Must start with a letter or underscore _
  • Can contain letters, numbers, and underscores
  • Cannot contain spaces or special characters
  • Case sensitive (age ≠ Age)
  • Cannot be C# keywords (if, for, int, class, etc.)
  • Convention: use camelCase for variables and PascalCase for classes

📊 Data Types

C# has several basic (primitive) data types. Here are the main types available in C#:

using System;

class Program {
    static void Main() {
        // Types entiers
        char c = 'A';              // 16 bits (Unicode)
        short s = 100;              // 16 bits
        int i = 1000;               // 32 bits
        long l = 100000L;           // 64 bits
        
        // Types entiers non signés
        byte b = 200;               // 8 bits (0 à 255)
        ushort us = 5000;           // 16 bits non signés
        uint ui = 5000U;            // 32 bits non signés
        ulong ul = 100000UL;        // 64 bits non signés
        
        // Types décimaux
        float f = 3.14f;            // 32 bits (simple précision)
        double d = 3.14159;         // 64 bits (double précision)
        decimal dec = 3.141592653589793m;  // 128 bits (haute précision)
        
        // Type booléen
        bool estVrai = true;
        bool estFaux = false;
        
        // Chaînes de caractères
        string chaine = "Hello";    // Chaîne de caractères
        string texte = "World";     // Chaîne de caractères
        
        // Affichage avec Console.WriteLine
        Console.WriteLine($"char: {c}");
        Console.WriteLine($"int: {i}");
        Console.WriteLine($"float: {f:F2}");
        Console.WriteLine($"double: {d}");
        Console.WriteLine($"bool: {estVrai}");
        Console.WriteLine($"chaine: {chaine}");
        
        // Taille des types (en octets)
        Console.WriteLine($"Taille de int: {sizeof(int)} octets");
        Console.WriteLine($"Taille de float: {sizeof(float)} octets");
        Console.WriteLine($"Taille de double: {sizeof(double)} octets");
    }
}

📚 C# Data Types:

  • int - Integer (4 bytes)
  • float - Single precision decimal number (4 bytes)
  • double - Double precision decimal number (8 bytes)
  • decimal - High precision decimal number (16 bytes)
  • char - Character (2 bytes, Unicode)
  • string - Character string
  • bool - Boolean (true/false)
  • byte - Unsigned byte (0 to 255)
  • object - Base type for all types

🔢 Operators

C# supports arithmetic, comparison, logical, assignment, and pointer operators:

using System;

class Program {
    static void Main() {
        int a = 10, b = 3;
        
        // Opérateurs arithmétiques
        Console.WriteLine($"{a} + {b} = {a + b}");      // Addition: 13
        Console.WriteLine($"{a} - {b} = {a - b}");      // Soustraction: 7
        Console.WriteLine($"{a} * {b} = {a * b}");      // Multiplication: 30
        Console.WriteLine($"{a} / {b} = {a / b}");      // Division entière: 3
        Console.WriteLine($"{a} % {b} = {a % b}");      // Modulo (reste): 1
        
        // Division avec double
        double resultat = (double)a / b;
        Console.WriteLine($"{a} / {b} = {resultat:F2}"); // Division: 3.33
        
        // Puissance (nécessite System.Math)
        double puissance = Math.Pow(a, b);
        Console.WriteLine($"{a}^{b} = {puissance:F0}");  // Puissance: 1000
        
        // Opérateurs de comparaison
        Console.WriteLine($"{a} > {b} = {a > b}");      // true
        Console.WriteLine($"{a} < {b} = {a < b}");      // false
        Console.WriteLine($"{a} >= {b} = {a >= b}");    // true
        Console.WriteLine($"{a} <= {b} = {a <= b}");    // false
        Console.WriteLine($"{a} == {b} = {a == b}");     // false
        Console.WriteLine($"{a} != {b} = {a != b}");    // true
        
        // Opérateurs logiques
        bool x = true, y = false;
        Console.WriteLine($"{x} && {y} = {x && y}");    // ET logique: false
        Console.WriteLine($"{x} || {y} = {x || y}");    // OU logique: true
        Console.WriteLine($"!{x} = {!x}");              // NON logique: false
        
        // Opérateurs d'assignation
        int c = 5;
        c += 3;  // Équivalent à c = c + 3 (c devient 8)
        c -= 2;  // Équivalent à c = c - 2 (c devient 6)
        c *= 2;  // Équivalent à c = c * 2 (c devient 12)
        c /= 3;  // Équivalent à c = c / 3 (c devient 4)
        c %= 3;  // Équivalent à c = c % 3 (c devient 1)
        
        // Opérateurs d'incrémentation/décrémentation
        int i = 5;
        Console.WriteLine($"i = {i++}");  // Post-incrémentation: affiche 5, puis i = 6
        Console.WriteLine($"i = {++i}");  // Pré-incrémentation: i = 7, puis affiche 7
    }
}

🔀 Conditional Structures

The C# language uses if, else if, and else for conditions. Code blocks are delimited by braces {}.

using System;

class Program {
    static void Main() {
        // Structure if simple
        int age = 20;
        
        if (age >= 18) {
            Console.WriteLine("Vous êtes majeur");
        } else {
            Console.WriteLine("Vous êtes mineur");
        }
        
        // Structure if/else if/else
        age = 15;
        
        if (age >= 18) {
            Console.WriteLine("Vous êtes majeur");
            Console.WriteLine("Vous pouvez voter");
        } else if (age >= 13) {
            Console.WriteLine("Vous êtes adolescent");
        } else if (age >= 6) {
            Console.WriteLine("Vous êtes enfant");
        } else {
            Console.WriteLine("Vous êtes un bébé");
        }
        
        // Conditions multiples
        int note = 85;
        string mention;
        
        if (note >= 90) {
            mention = "Excellent";
        } else if (note >= 80) {
            mention = "Très bien";
        } else if (note >= 70) {
            mention = "Bien";
        } else if (note >= 60) {
            mention = "Assez bien";
        } else {
            mention = "Insuffisant";
        }
        
        Console.WriteLine($"Votre mention : {mention}");
        
        // Opérateur ternaire (expression conditionnelle)
        age = 20;
        string statut = age >= 18 ? "Majeur" : "Mineur";
        Console.WriteLine(statut);
        
        // Conditions avec &&/||
        age = 25;
        bool permis = true;
        
        if (age >= 18 && permis) {
            Console.WriteLine("Vous pouvez conduire");
        } else {
            Console.WriteLine("Vous ne pouvez pas conduire");
        }
    }
}

🔄 Loops

The C# language offers several types of loops: for (to iterate a defined number of times), while (to repeat while a condition is true), do-while (executes at least once), and foreach (to iterate through collections):

using System;

class Program {
    static void Main() {
        // Boucle for
        for (int i = 0; i < 5; i++) {
            Console.WriteLine(i);  // Affiche 0, 1, 2, 3, 4
        }
        
        // for avec début et fin
        for (int i = 1; i <= 5; i++) {
            Console.WriteLine(i);  // Affiche 1, 2, 3, 4, 5
        }
        
        // for avec pas
        for (int i = 0; i < 10; i += 2) {
            Console.WriteLine(i);  // Affiche 0, 2, 4, 6, 8
        }
        
        // Boucle foreach avec liste
        string[] fruits = {"pomme", "banane", "orange"};
        foreach (string fruit in fruits) {
            Console.WriteLine($"J'aime les {fruit}");
        }
        
        // Boucle for avec index
        string[] fruits2 = {"pomme", "banane", "orange"};
        for (int index = 0; index < fruits2.Length; index++) {
            Console.WriteLine($"{index}: {fruits2[index]}");
        }
        
        // Boucle while
        int compteur = 0;
        while (compteur < 5) {
            Console.WriteLine(compteur);
            compteur++;
        }
        
        // Boucle while avec break
        compteur = 0;
        while (true) {
            Console.WriteLine(compteur);
            compteur++;
            if (compteur >= 5) {
                break;  // Sortir de la boucle
            }
        }
        
        // continue (passer à l'itération suivante)
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {  // Si i est pair
                continue;      // Passer au suivant
            }
            Console.WriteLine(i);  // Affiche seulement les impairs: 1, 3, 5, 7, 9
        }
        
        // Boucle do-while
        int j = 0;
        do {
            Console.WriteLine(j);
            j++;
        } while (j < 5);
    }
}

⚙️ Methods

Methods allow code reuse. In C#, we define a method with its return type, name, and parameters. Methods can take parameters and return values with return.

using System;

class Program {
    // Méthode simple (sans paramètres)
    static void DireBonjour() {
        Console.WriteLine("Bonjour !");
    }
    
    // Méthode avec paramètres
    static string Saluer(string nom) {
        return $"Bonjour, {nom} !";
    }
    
    // Méthode avec plusieurs paramètres
    static int Additionner(int a, int b) {
        return a + b;
    }
    
    // Méthode avec paramètres par défaut
    static string SaluerPersonne(string nom, string message = "Bonjour") {
        return $"{message}, {nom} !";
    }
    
    // Méthode avec params (arguments variables)
    static int AdditionnerNombres(params int[] nombres) {
        int somme = 0;
        foreach (int n in nombres) {
            somme += n;
        }
        return somme;
    }
    
    static void Main() {
        DireBonjour();  // Appel de la méthode
        
        string message = Saluer("C#");
        Console.WriteLine(message);  // "Bonjour, C# !"
        
        int resultat = Additionner(5, 3);
        Console.WriteLine(resultat);  // 8
        
        Console.WriteLine(SaluerPersonne("Bassirou"));              // "Bonjour, Bassirou !"
        Console.WriteLine(SaluerPersonne("Bassirou", "Salut"));     // "Salut, Bassirou !"
        
        Console.WriteLine(AdditionnerNombres(1, 2, 3, 4, 5));  // 15
    }

    }
}

🏛️ Classes and Objects

In C#, everything is object-oriented. Classes allow creating custom types with properties and methods.

using System;

// Définition d'une classe
public class Personne {
    // Propriétés
    public string Nom { get; set; }
    public int Age { get; set; }
    public double Taille { get; set; }
    
    // Constructeur
    public Personne(string nom, int age, double taille) {
        Nom = nom;
        Age = age;
        Taille = taille;
    }
    
    // Méthode
    public void Afficher() {
        Console.WriteLine($"Nom: {Nom}, Age: {Age}, Taille: {Taille}m");
    }
}

class Program {
    static void Main() {
        // Création d'objets
        Personne p1 = new Personne("Bassirou", 25, 1.75);
        Personne p2 = new Personne("Aminata", 30, 1.65);
        
        p1.Afficher();
        p2.Afficher();
    }
}

📦 Collections

C# offers several types of collections: List, Dictionary, HashSet, Queue, Stack, etc.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        // List - Liste dynamique
        List nombres = new List {1, 2, 3, 4, 5};
        nombres.Add(6);
        nombres.Remove(3);
        
        foreach (int n in nombres) {
            Console.WriteLine(n);
        }
        
        // Dictionary - Dictionnaire clé-valeur
        Dictionary ages = new Dictionary();
        ages["Bassirou"] = 25;
        ages["Aminata"] = 30;
        
        foreach (var kvp in ages) {
            Console.WriteLine($"{kvp.Key}: {kvp.Value} ans");
        }
        
        // HashSet - Ensemble unique
        HashSet noms = new HashSet {"Alice", "Bob", "Alice"};
        Console.WriteLine($"Nombre d'éléments: {noms.Count}"); // 2 (Alice en double)
    }
}

🔗 Inheritance

Inheritance allows a class to derive from another class and inherit its members.

using System;

// Classe de base
public class Animal {
    public string Nom { get; set; }
    
    public virtual void FaireDuBruit() {
        Console.WriteLine($"{Nom} fait un bruit");
    }
}

// Classe dérivée
public class Chien : Animal {
    public Chien(string nom) {
        Nom = nom;
    }
    
    public override void FaireDuBruit() {
        Console.WriteLine($"{Nom} aboie");
    }
}

class Program {
    static void Main() {
        Chien chien = new Chien("Rex");
        chien.FaireDuBruit(); // "Rex aboie"
    }
}

🔌 Interfaces

Interfaces define a contract that classes must implement. A class can implement multiple interfaces.

using System;

// Définition d'une interface
public interface IVoler {
    void Voler();
}

public interface INager {
    void Nager();
}

// Classe implémentant plusieurs interfaces
public class Canard : IVoler, INager {
    public void Voler() {
        Console.WriteLine("Le canard vole");
    }
    
    public void Nager() {
        Console.WriteLine("Le canard nage");
    }
}

class Program {
    static void Main() {
        Canard canard = new Canard();
        canard.Voler();
        canard.Nager();
    }
}

🔍 LINQ (Language Integrated Query)

LINQ allows querying collections in a declarative and expressive way.

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main() {
        List nombres = new List {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        // Filtrer les nombres pairs
        var pairs = nombres.Where(n => n % 2 == 0);
        
        // Calculer la somme
        int somme = nombres.Sum();
        
        // Trouver le maximum
        int max = nombres.Max();
        
        // Trier
        var trie = nombres.OrderByDescending(n => n);
        
        // Sélectionner et transformer
        var carres = nombres.Select(n => n * n);
        
        Console.WriteLine($"Somme: {somme}, Max: {max}");
    }
}

⚡ Asynchronous Programming

C# supports asynchronous programming with async/await for non-blocking operations.

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        await TéléchargerDonnées();
    }
    
    static async Task TéléchargerDonnées() {
        using (HttpClient client = new HttpClient()) {
            string resultat = await client.GetStringAsync("https://api.example.com/data");
            Console.WriteLine(resultat);
        }
    }
}

💡 Note importante : C# utilise un garbage collector (GC) pour gérer automatiquement la mémoire. Vous n'avez pas besoin de libérer manuellement la mémoire comme en C/C++. Le GC s'occupe de libérer les objets non utilisés automatiquement.

🎓 Next Steps

Congratulations! You now have a solid foundation in C#.

✅ What you have learned:

  • C# syntax and variables
  • Data types (int, float, double, string, bool)
  • Operators (arithmetic, comparison, logical)
  • Conditional structures (if, else if, else, switch)
  • Loops (for, while, do-while, foreach)
  • Methods (definition, parameters, return)
  • Classes and objects (encapsulation, constructors)
  • Inheritance and interfaces
  • Collections (List, Dictionary, etc.)
  • LINQ and async/await

🚀 To go further:

  • 📚 ASP.NET Core - Web development with C#
  • 🔧 Entity Framework - ORM for databases
  • 📦 NuGet - .NET package manager
  • 🌐 REST API - API creation with ASP.NET Core
  • 📊 Advanced LINQ - Complex queries
  • 🤖 Unity - Game development with C#
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?