272 lines
4.8 KiB
Markdown
272 lines
4.8 KiB
Markdown
# Petite liste d’exemples de styles modernes en C# (C# 8 → C# 12)
|
||
|
||
## 🔹 1. Opérateur ternaire (version concise) (if/else)
|
||
|
||
```csharp
|
||
var statut = age >= 18 ? "Majeur" : "Mineur";
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 2. `switch` expression (moderne)
|
||
|
||
```csharp
|
||
// Le _ remplace default.
|
||
|
||
// Exemple simple
|
||
var codeErreur = 500;
|
||
string message = codeErreur switch
|
||
{
|
||
404 => "Introuvable",
|
||
401 => "Non autorisé",
|
||
500 => "Erreur serveur",
|
||
_ => "Erreur inconnue"
|
||
};
|
||
|
||
// Avec enum
|
||
enum Statut { Actif, Inactif, Suspendu }
|
||
Statut statut = Statut.Actif;
|
||
string message = statut switch
|
||
{
|
||
Statut.Actif => "Utilisateur actif",
|
||
Statut.Inactif => "Utilisateur inactif",
|
||
Statut.Suspendu => "Compte suspendu",
|
||
_ => "Statut inconnu"
|
||
};
|
||
|
||
// Avec conditions (patterns relationnels)
|
||
int age = 20;
|
||
string categorie = age switch
|
||
{
|
||
< 12 => "Enfant",
|
||
>= 12 and < 18 => "Adolescent",
|
||
>= 18 => "Adulte"
|
||
};
|
||
|
||
// Avec expression conditionnelle imbriquée :
|
||
var note = score switch
|
||
{
|
||
>= 16 => "Très bien",
|
||
>= 12 => "Bien",
|
||
>= 10 => "Passable",
|
||
_ => "Insuffisant"
|
||
};
|
||
|
||
// Avec when (pattern guard)
|
||
int note = 15;
|
||
string resultat = note switch
|
||
{
|
||
int n when n >= 16 => "Très bien",
|
||
int n when n >= 12 => "Bien",
|
||
int n when n >= 10 => "Passable",
|
||
_ => "Échec"
|
||
};
|
||
|
||
// Switch sur string
|
||
string pays = "FR";
|
||
string langue = pays switch
|
||
{
|
||
"FR" => "Français",
|
||
"EN" => "Anglais",
|
||
"ES" => "Espagnol",
|
||
_ => "Inconnue"
|
||
};
|
||
|
||
// Switch avec tuple
|
||
int x = 0, y = 5;
|
||
string position = (x, y) switch
|
||
{
|
||
(0, 0) => "Origine",
|
||
(0, _) => "Axe Y",
|
||
(_, 0) => "Axe X",
|
||
_ => "Plan"
|
||
};
|
||
|
||
// Switch avec type pattern
|
||
object obj = "Bonjour";
|
||
string description = obj switch
|
||
{
|
||
int i => $"Entier : {i}",
|
||
string s => $"Chaîne : {s}",
|
||
null => "Null",
|
||
_ => "Autre type"
|
||
};
|
||
|
||
// etc
|
||
// ...
|
||
```
|
||
|
||
|
||
---
|
||
|
||
## 🔹 3. Parcourir un tableau / liste
|
||
|
||
### `foreach` (simple et propre)
|
||
|
||
```csharp
|
||
foreach (var item in items)
|
||
{
|
||
Console.WriteLine(item);
|
||
}
|
||
```
|
||
|
||
### LINQ (fonctionnel)
|
||
|
||
```csharp
|
||
items
|
||
.Where(i => i.IsActive)
|
||
.Select(i => i.Name)
|
||
.ToList()
|
||
.ForEach(Console.WriteLine);
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 4. Création d’objet (init rapide)
|
||
|
||
### Initialiseur d’objet
|
||
|
||
```csharp
|
||
var user = new User
|
||
{
|
||
Id = 1,
|
||
Name = "Alice",
|
||
IsAdmin = true
|
||
};
|
||
```
|
||
|
||
### Constructeur concis (target-typed `new`)
|
||
|
||
```csharp
|
||
User user = new(1, "Alice", true);
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 5. `record` (objets immuables – très moderne)
|
||
|
||
```csharp
|
||
public record User(int Id, string Name, bool IsAdmin);
|
||
```
|
||
|
||
Utilisation :
|
||
|
||
```csharp
|
||
// User(int id, string name, bool isAdmin)
|
||
var user = new User(1, "Alice", false);
|
||
// Retourn false.
|
||
var admin = user with { IsAdmin = true };
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 6. Null safety (très utilisé)
|
||
|
||
### Opérateur `?.`
|
||
|
||
```csharp
|
||
// Si user == null alors on n'accède pas à Name
|
||
// Si Name == null alors on n'accède pas à Length
|
||
var length = user?.Name?.Length;
|
||
```
|
||
|
||
### Coalescence `??`
|
||
|
||
```csharp
|
||
// Si user.Name == null alors on assigne "Inconnu"
|
||
string name = user.Name ?? "Inconnu";
|
||
```
|
||
|
||
### Affectation conditionnelle `??=`
|
||
|
||
```csharp
|
||
// Si null alors on assigne.
|
||
user.Name ??= "Par défaut";
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 7. Expressions lambda
|
||
|
||
```csharp
|
||
Func<int, int> carre = x => x * x;
|
||
Console.WriteLine(carre(5));
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 8. Pattern matching
|
||
|
||
```csharp
|
||
if (obj is User { IsAdmin: true })
|
||
{
|
||
Console.WriteLine("Admin détecté");
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 9. Tableaux et collections modernes
|
||
|
||
### Création simplifiée (C# 9+)
|
||
|
||
```csharp
|
||
int[] nombres = { 1, 2, 3, 4 };
|
||
```
|
||
|
||
### Range & Index
|
||
|
||
```csharp
|
||
int[] nombres = { 1, 2, 3, 4, 5 };
|
||
|
||
// INDEX (^) – à partir de la fin
|
||
var ... = nombres[^1]; // dernier élément → 5
|
||
var ... = nombres[^2]; // avant-dernier → 4
|
||
var ... = nombres[^3]; // retourne 3
|
||
|
||
// RANGE (..) – sous-tableaux
|
||
var ... = nombres[1..4]; // {2, 3, 4}
|
||
// Un seul élément via Range
|
||
var ... = nombres[2..3]; // {3}
|
||
// Début → Fin du tableau
|
||
var ... = nombres[2..]; // {3, 4, 5}
|
||
// Début du tableau → Fin
|
||
var ... = nombres[..3]; // {1, 2, 3}
|
||
// Début → Fin (exclus)
|
||
var sousTableau = nombres[1..4]; // {2, 3, 4}
|
||
// Tout le tableau
|
||
var ... = nombres[..]; // {1, 2, 3, 4, 5}
|
||
// Range avec Index depuis la fin
|
||
var ... = nombres[1..^1]; // {2, 3, 4}
|
||
// Derniers éléments
|
||
var ... = nombres[^2..]; // {4, 5}
|
||
// Tout sauf les deux derniers
|
||
var ... = nombres[..^2]; // {1, 2, 3}
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 10. Méthodes d’expression (très clean)
|
||
|
||
```csharp
|
||
int Add(int a, int b) => a + b;
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 11. `using` moderne (sans bloc)
|
||
|
||
```csharp
|
||
using var file = new StreamWriter("test.txt");
|
||
file.WriteLine("Hello");
|
||
```
|
||
|
||
---
|
||
|
||
## 🔹 12. Collections immuables rapides
|
||
|
||
```csharp
|
||
// Création d'un tableau de string
|
||
var fruits = new[] { "Pomme", "Banane", "Orange" };
|
||
```
|