Langage C#

L'essentiel du langage C#: syntaxe, fonctions et exemples

{0}, {1}, ...
Placeholders numérotés pour String.Format
csharp
string name = "John";
int age = 30;
string message = string.Format("Hello, {0}! You are {1} years old.", name, age);
$"...{var}..."
Chaînes interpolées (C# 6+)
csharp
string name = "John";
int age = 30;
string message = $"Hello, {name}! You are {age} years old.";
{0:d}
Format entier décimal
csharp
int number = 42;
string formatted = string.Format("{0:d}", number);
{0:f2}
Format nombre à virgule flottante avec 2 décimales
csharp
double pi = 3.14159;
string formatted = string.Format("{0:f2}", pi); // "3.14"
{0:c}
Format monétaire
csharp
decimal price = 123.45m;
string formatted = string.Format("{0:c}", price); // "$123.45" (dépend de la culture)
{0:p}
Format pourcentage
csharp
double ratio = 0.25;
string formatted = string.Format("{0:p}", ratio); // "25.00%"
{0:n}
Format nombre avec séparateurs de milliers
csharp
int number = 1234567;
string formatted = string.Format("{0:n0}", number); // "1,234,567"
{0:x}
Format hexadécimal (minuscules)
csharp
int number = 255;
string formatted = string.Format("{0:x}", number); // "ff"
{0:X}
Format hexadécimal (majuscules)
csharp
int number = 255;
string formatted = string.Format("{0:X}", number); // "FF"
{0:dd/MM/yyyy}
Format date personnalisé
csharp
DateTime date = new DateTime(2023, 12, 31);
string formatted = string.Format("{0:dd/MM/yyyy}", date); // "31/12/2023"
{0,10}
Alignement à droite (largeur 10)
csharp
string text = "Hello";
string formatted = string.Format("{0,10}", text); // "     Hello"
{0,-10}
Alignement à gauche (largeur 10)
csharp
string text = "Hello";
string formatted = string.Format("{0,-10}", text); // "Hello     "
Console.WriteLine()
Afficher du texte sur la console
csharp
Console.WriteLine("Hello, World!");
Console.WriteLine("Value: {0}", 42);
Console.WriteLine($"Value: {42}");