Skip to content

Instantly share code, notes, and snippets.

@yostane
Last active March 29, 2023 14:47
Show Gist options
  • Save yostane/4faf58bf1660b141e2ef100ad60502f7 to your computer and use it in GitHub Desktop.
Save yostane/4faf58bf1660b141e2ef100ad60502f7 to your computer and use it in GitHub Desktop.
Bouts de code c#
Console.Write("Hello");
int i = 0;
string s = "Hello";
float f = 1.3F;
double d = 3.0;
bool b = true;
var k = 20; // typage implicite
//k = "toto"; // erreur
string chaine = $"un entier {i}. Une autre var {s}";
Console.WriteLine(chaine);
Console.WriteLine("un entier {i}. Une autre var {s}");
Console.WriteLine($"Expression {i + 3}");
Console.WriteLine($"Expression {i = 9 + 12} - i = {i}");
Console.WriteLine($"Expression {i == 9}");
Console.WriteLine($"Expression {i == 21}");
int x = new Random().Next(100);
Console.WriteLine(x);
if (x > 50)
{
Console.WriteLine("Above");
}
else
{
Console.WriteLine("Below");
}
switch (x)
{
case 0:
Console.WriteLine("Zero");
break;
case 2:
case 3:
Console.WriteLine("Two or three");
break;
case 50:
Console.WriteLine("Average");
break;
default:
Console.WriteLine("default");
break;
}
Console.WriteLine("First loop");
int i = 10;
while (i > 0)
{
Console.WriteLine(i);
i -= 1;
}
Console.WriteLine("Second loop");
i = 0;
while (i < 10)
{
Console.WriteLine(i);
i += 1;
}
Console.WriteLine("Rewrite second loop with for syntax");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
var s = "Please loop me";
foreach (var c in s)
{
Console.Write($"{c} - ");
}
void SayPika()
{
Console.WriteLine("Pika");
}
int Add(int a, int b)
{
return a + b;
}
// One line function ou fonction expression
int Multiply(int a, int b) => a * b;
void SayPikaOneLine(string message) => Console.WriteLine($"PIKAAAAAACHUUUU {message}");
bool IsAlive(int hp) => hp > 0;
SayPika();
Console.WriteLine(Add(3, 5));
Console.WriteLine(Multiply(3, 5));
var f = Multiply;
Console.WriteLine(f(10, 30));
Console.WriteLine(f(-9, 2));
Console.WriteLine(f);
Func<int, int, int> g = Add;
Predicate<int> p = IsAlive;
Action s = SayPika;
Action<string> sa = SayPikaOneLine;
sa("vive c#");
int DivideD(double a, double b) => (int)(a / b);
void SayPikaTwoLines(string line1, string line2)
{
Console.WriteLine($"PIKAAAAAACHUUUU {line1}");
Console.WriteLine($"PIKA {line2}");
}
bool IsPalindrome(string s) => s.Reverse() == s;
Console.WriteLine(DivideD(10, 2));
// Fonction d'ordre supérieur (higher order function)
void PrintComputation(Func<int, int, int> f)
{
int result1 = f(10, 11);
int result2 = f(-4, 2);
Console.WriteLine($"calcul 1 = {result1}. Calcul 2 = {result2}");
}
// f = Multiply, g = Add
PrintComputation(Add);
PrintComputation(Multiply);
PrintComputation(g);
PrintComputation(f);
int Subsctract(int a, int b) => a - b;
PrintComputation(Subsctract);
// Lambda (ou fonction anonyme) dans une variable
Func<int, int, int> sub = (a, b) =>
{
return a - b;
};
PrintComputation(sub);
PrintComputation((x, y) => x - y);
void PrintComputation2(int a, int b, Func<int, int, int> f)
{
int result1 = f(a, b);
int result2 = f(-4, 2);
Console.WriteLine($"calcul 1 = {result1}. Calcul 2 = {result2}");
}
PrintComputation2(10, 2, Add);
PrintComputation2(10, 2, Multiply);
PrintComputation2(10, 2, g);
PrintComputation2(10, 2, f);
// appeler PrintComputation2 en passant une lambda qui fait la soustraction
PrintComputation2(2, 10, (x, y) => x - y);
PrintComputation2(2, 10, (toto, tutu) =>
{
return toto - tutu;
});
Func<int> GenerateIncrementer(int initialValue, int increment)
{
int currentValue = initialValue;
int Increment()
{
currentValue += increment;
return currentValue;
}
return Increment;
}
Func<int> inc1 = GenerateIncrementer(0, 5);
Console.WriteLine(inc1());
Console.WriteLine(inc1());
Console.WriteLine(inc1());
var inc2 = GenerateIncrementer(-10, 4);
Console.WriteLine(inc2());
Console.WriteLine(inc2());
Console.WriteLine(inc2());ne(Add(3, 5));
Console.WriteLine(Multiply(3, 5));
abstract class YuGiOhCard
{
public YuGiOhCard(string name, string description, int rank, bool isHidden)
{
this.Name = name;
this.Description = description;
this.Rank = rank;
this.IsHidden = isHidden;
}
// 1 - créer une variable privée du avec _ en préfixe (backing field)
private string _Name;
// 2- définir une propriété publique avec des acccesseurs
public string Name
{
get
{
Console.WriteLine("lecture");
return _Name;
}
set
{
Console.WriteLine($"ecriture {value}");
_Name = value;
}
}
private string _Description;
// synthetiser _Description
public string Description
{
get { return this._Description; }
set { this._Description = value; }
}
public int Rank { get; set; }
public bool IsHidden { get; set; }
}
class MagicCard : YuGiOhCard
{
public MagicCard(string effect, string name, string description, int rank, bool isHidden) : base(name, description, rank, isHidden)
{
this.Effect = effect;
}
public string Effect { get; set; }
}
class AttackCard : YuGiOhCard
{
public AttackCard(int attack, bool isDefense, string name, string description, int rank, bool isHidden) : base(name, description, rank, isHidden)
{
this.Attack = attack;
this.IsDefense = isDefense;
}
public int Attack { get; set; }
public bool IsDefense { get; set; }
}
AttackCard card = new AttackCard(10000, true, "Exodia", "Dragon aux yeux bleu", 10, false);
string name = card.Name;
Console.WriteLine($"name => {name}");
Console.WriteLine(card.Description);
Console.WriteLine(card.Rank);
MagicCard magicCard = new MagicCard("papillon", "carte magique", "fourchette", 4, true);
Console.WriteLine(magicCard.Name);
enum Meteo { Pluie, Neige, Soleil, Nuages, Tempete, Drache, Vent }
enum CategorieAge { Bebe, Adolescent, Adulte, Vieux }
Meteo etatDuJour = Meteo.Soleil;
CategorieAge categorieAge = CategorieAge.Adulte;
switch (categorieAge)
{
case CategorieAge.Adolescent:
break;
case CategorieAge.Adulte:
break;
case CategorieAge.Bebe:
break;
case CategorieAge.Vieux:
break;
}
switch (categorieAge)
{
case CategorieAge.Adolescent:
break;
case CategorieAge.Adulte:
break;
default:
break;
}
int[] numbers = { 5, -10, 0, 12, 55, 42, -2, 6, 5 };
Console.Write("Numbers: ");
foreach (int number in numbers)
{
Console.Write($"{number}, ");
}
Console.WriteLine();
Console.WriteLine(string.Join(", ", numbers));
string[] donaldNeveux = { "riri", "fifi", "loulou" };
Console.Write("Neveux de Donald: ");
foreach (var donaldNeveu in donaldNeveux)
{
Console.Write($"{donaldNeveu}, ");
}
Console.WriteLine();
Console.WriteLine(string.Join(" -- ", donaldNeveux));
int[] prices = { 10, 200, 1000 };
foreach (int price in prices)
{
Console.Write($"{price} - ");
}
Console.WriteLine();
Console.WriteLine($"Length: {prices.Length}. {prices.Last()}");
// rectangular array (tableau rectangulaire)
double[,] matrix4 = {
{1, 2, 4},
{10, 29, 41},
{13, 22, 41},
{9, 2, 8}
};
Console.WriteLine(matrix4);
foreach (var item in matrix4)
{
Console.WriteLine(item);
}
// trouver le maximum de la matrice
for (int i = 0; i < matrix4.GetLength(0); i++)
{
for (int j = 0; j < matrix4.GetLength(1); j++)
{
Console.WriteLine($"matrix4[{i}, {j}] => {matrix4[i, j]}");
}
}
// sparse array (tableau éparse)
int[][] tab = new int[3][];
tab[0] = new int[2];
tab[0][0] = 3;
tab[0][1] = 6;
tab[1] = new int[4];
tab[1][0] = 3;
tab[1][1] = 6;
tab[1][2] = 1;
tab[1][3] = -3;
tab[2] = new int[2];
tab[2][0] = -3;
tab[2][1] = -6;
Console.WriteLine("tab");
for (int i = 0; i < tab.Length; i++)
{
for (int j = 0; j < tab[i].Length; j++)
{
Console.WriteLine($"matrix4[{i}][{j}] => {tab[i][j]}");
}
}
using System;
using System.Threading.Tasks;
Console.WriteLine("hello");
void RunCallbackContinueWith()
{
void RunTask1(Action callback)
{
Task.Run(() =>
{
for (int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
callback();
});
}
void Callback1(Action callback)
{
Task.Run(() =>
{
Console.WriteLine("baby callback");
callback();
});
}
// la callback c'est un mécanisme qui permet à la fonction appelant de passer des
// traitements qui seront exécutés par la fonction appelée
RunTask1(() =>
{
Callback1(() =>
{
Console.WriteLine("ballback-ofduty"); // ! callback hell
});
});
Task.Run(() =>
{
for (int i = -1; i > -500; i--)
{
Console.WriteLine(i);
}
}).ContinueWith((antecedant) =>
{
// antecedant permet de d'avoir des infos sur la tâche appelante
Console.WriteLine("baby don't callback");
}).ContinueWith((antecedant) =>
{
Console.WriteLine("Flash-call-back");
});
}
// RunCallbackContinueWith();
// création d'une task. le await va suspndre le thread courant (sans le bloquer)
await Task.Run(() =>
{
for (int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
});
Console.WriteLine("callback in black");
// ce code sera exécuté une fois la task précedente se termine
await Task.Run(() =>
{
for (int i = -1; i > -500; i--)
{
Console.WriteLine(i);
}
});
Console.WriteLine("callback to future");
// ce code sera exécuté une fois que la task précedente se termine
Console.WriteLine("end");
using System;
using System.Threading.Tasks;
Console.WriteLine("lot 6 part 2");
var task1 = Task.Run(() =>
{
for (int i = 0; i < 50; i++)
{
Console.WriteLine(i);
}
return "tartatin";
});
Console.WriteLine($"{task1}, completed ? {task1.IsCompleted}. status {task1.Status}");
//await suspend jusqu'à la fin de la Task et donne son résultat dans le cas échéant.
// await fonctionne de pair avec Task
// await est un mot clé (il fait partie intégrale du langage c#)
var result = await task1;
await Task.Run(() =>
{
for (int i = -1; i > -10; i--)
{
Console.WriteLine(i);
}
});
Console.WriteLine($"{task1}, completed ? {task1.IsCompleted}. status {task1.Status}");
var task3 = new Task(() =>
{
for (int i = -10; i > -20; i--)
{
Console.WriteLine(i);
}
});
Console.WriteLine($"task status {task3.Status}");
task3.Start();
Console.WriteLine($"task status {task3.Status}");
await task3;
Console.WriteLine($"task status {task3.Status}");
Console.WriteLine("Orange is the new callback");
using System;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
Console.WriteLine("lot 6 part 3 et 4");
// convention: fonction qui retourne une Task doit avoir le suffixe async
Task<string> TestAsync()
{
return Task.Run(() =>
{
for (int i = 0; i < 50; i++)
{
Console.WriteLine(i);
}
return "callback me maybe";
});
}
var s = await TestAsync();
System.Console.WriteLine(s);
HttpClient client = new();
var x = await client.GetAsync("https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching");
System.Console.WriteLine(await x.Content.ReadAsStringAsync());
// GetPageContentAsync est intrinsèqument asynchrone, donc c'est une Task (car elle await des Task)
// => ça veut dire qu'elle doit retourer Task ou Task<type>
// Une fonction qui fait des "await" doit avoir "async" dans sa signature
async Task<string> GetPageContentAsync(string url)
{
HttpClient client = new();
var x = await client.GetAsync(url);
return await x.Content.ReadAsStringAsync();
}
// soit async Task soit async void. Ne mettre 'async void' que si 'async Task' génère une erreur
async Task ShowPageContentAsync(string url)
{
HttpClient client = new();
var x = await client.GetAsync(url);
System.Console.WriteLine(await x.Content.ReadAsStringAsync());
}
const string url = "https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching";
System.Console.WriteLine(await GetPageContentAsync(url));
Console.WriteLine("I'll be callback");
class LolFighter
{
public string Name { get; set; }
public int Hp { get; set; }
public int Level { get; set; }
public LolFighter(string name, int hp)
{
this.Name = name;
this.Hp = hp;
}
// optionnel
override public string ToString() => $"lvl{this.Level} {this.Name}, {this.Hp} hp";
}
var lolFighter = new LolFighter("Garen", 1000);
lolFighter.Level = 1;
//setup properties and initialize prop in a single statement
var lolFighter2 = new LolFighter("leona", 900)
{
Level = 1
};
Console.WriteLine(lolFighter);
Console.WriteLine(lolFighter2);
using System;
var c = new Circle(1.0);
Circle c2 = new(1.0);
Console.WriteLine(c);
Console.WriteLine(c.Equals(c2));
Console.WriteLine(c == c2);
class Circle
{
public Circle(double radius)
{
this.Radius = radius;
}
public double Radius { get; set; }
public double Area { get => Math.Pow(Radius, 2) * Math.PI; }
public double Circumference => Radius * Math.PI * 2;
public double Diameter => 2 * Radius;
public override string ToString() => $"[Circle]=> Radius: {this.Radius}, Area: {Area:0.####} ...";
// override object.Equals
public override bool Equals(object obj)
{
if (obj is not null and Circle c)
{
return c.Radius == this.Radius;
}
else
{
return false;
}
}
public static bool operator ==(Circle c1, Circle c2) => c1.Equals(c2);
public static bool operator !=(Circle c1, Circle c2) => !c1.Equals(c2);
}
#nullable enable
int i = 0;
// i = "hello"; // erreur car le typage est statique (le type d'une variable ne change pas)
// on peut faire du dynamique avec object ou dynamic
// ! à ne pas faire chez vous
object vvv = "hello";
vvv = 12;
dynamic zzzz = 12;
zzzz = "Hello";
string textNonNull = null; // erreur
// avec les null checks, il faut rajouter ? pour permettre à un type d'accepter 'null'
// ! ajouter le '?' que quand c'est nécessaire
string? s = "Hello";
s = null;
// chainage null -> permet de retourner null dès qu'un appel retourne null
// dispo avant c#9 et n'est pas lié à la null safety
Console.WriteLine(s?.ToUpper()?.Length);
if (s is not null)
{
// avec les null checks, je dois être dans un contexte non null
Console.WriteLine(s.Length);
}
// on peut outrepasser le null checks avec ! (on dit au compilateur que c'est pas null)
// ! ne pas faire chez vous
Console.WriteLine(s!.Length);
using System;
using System.Collections.Generic;
using System.Linq;
int a = 10;
int Add(int a = 5, int b = -5) => a + b;
int Multiply(int a, int b) => a * b;
bool IsPair(int x) => x % 2 == 0;
// en c# les fonctions sont des éléments de première classe
Func<int, int, int> f = Add;
Console.WriteLine(Add(10, 212));
Console.WriteLine(f(10, 10));
f = Multiply;
Console.WriteLine(f(5, 5));
// f = IsPair; // erreur car pas la même signature
// on délègue le calcul sur a et b à une autre fonction
// printResult est un fonction d'ordre plus élevé (higher order function)
void printResult(int a, int b, Func<int, int, int> f)
{
Console.WriteLine($"Voici le résultat {f(a, b)}");
}
printResult(10, 1, Add);
printResult(10, 1, Multiply);
// expression lambda
printResult(-11, 6, (x, y) =>
{
return x / y;
});
printResult(-11, 7, (x, y) => x / y);
// Génération de fonctions à la volée
Func<int, int> createIncrementer(int increment)
{
return (x) => x + increment;
}
var inc1 = createIncrementer(1);
Console.WriteLine(inc1(10));
Console.WriteLine(inc1(25));
Func<int, int> inc2 = createIncrementer(-10);
Console.WriteLine(inc2(10));
Console.WriteLine(inc2(25));
// Le fonctionnel encourage la non mutabilité
// mutabilité => la modification se fait directement sur la variable (peut être négatif pour certains car on accepte que certains champs changement de façon invisible)
// non-mutabilité => on ne peut pas modifier une variable. La modification consisite à faire une copie et à changer les valeurs sur la copies à sa création
MutableCircle mc = new() { Radius = 10, Color = "Blue" };
mc.Radius = 20; // mutabilité
MutableCircle mc2 = new() { Radius = mc.Radius, Color = "Red" }; // non mutabilité = changement => nouvel objet
Console.WriteLine(mc2);
Circle c1 = new(10, "Yellow");
Circle c2 = c1 with { Color = "Purple" };
Console.WriteLine(c1);
Console.WriteLine(c2);
Circle c3 = new();
// Traitement en chaine,
// style de programmation déclaratif => y = f(x) (exemples: Fonctionnel, Redux, Flutter)
List<int> items = new() { 1, 2, 3, 4, 5, 6, 7, 8 };
// on prend les entiers pairs, on fait la puissance 2 et on fait la somme
int resultat = items.Where((item) => item % 2 == 0).Select((item) => item * item).Aggregate((current, acc) => current + acc);
// impératif
int somme = 0;
foreach (var item in items)
{
if (item % 2 == 0)
{
somme += item * item;
}
}
class MutableCircle
{
public int Radius { get; set; }
public string Color { get; set; } = "Yolo";
}
record Circle(int Raduis = 5, string Color = "Burgundy");
using System;
var card = new YuGiOhCard();
card.Description = "hello";
Console.WriteLine(card.Description);
class YuGiOhCard
{
public YuGiOhCard()
{
}
private string _firstName;
private string _lastName;
public string FullName
{
get
{
return $"{_firstName} {_lastName}";
}
}
// champ: une valeur associée à la classe
private string _description;
// => une propriété expose un champ
public string Description
{
get
{
return this._description.ToLower();
}
set
{
this._description = value;
}
}
// propriété: tout ce qui expose un champ via getter et setter
public int Attack { get; set; } // auto-synthétisé
// à utiliser dorénavant
}
// Collection: structure de données qui permet de gérer un ensemble de valeurs
List<string> words = new List<string> { "hello", "world" };
words.Add("!");
words.Remove("hello");
words.RemoveAt(0);
Console.WriteLine(words[0]);
var data = new Dictionary<string, int>
{
["age"] = 55,
["temperature"] = 37
};
data["money"] = 1000;
Console.WriteLine(data["age"]);
int[] numbers = { 1, 10, -80 };
int somme = 0;
foreach (int number in numbers)
{
if (number > 0)
{
somme += number * 2;
}
}
Console.WriteLine(somme);
// filter, map, reduce
// LINQ .net => where, selet, aggregate
var step1Items = numbers.Where((number) => number > 0);
Console.WriteLine(string.Join(" , ", step1Items));
var step2Items = step1Items.Select((number) => number * 2);
Console.WriteLine(string.Join(" , ", step2Items));
var result = step2Items.Aggregate((acc, cur) => acc + cur);
Console.WriteLine(result);
var result2 = numbers.AsParallel().Where((number) => number > 0)
.Select((number) => number * 2)
.Aggregate((value, acc) => acc + value);
Console.WriteLine(result2);
using System;
int add(int a, int b)
{
return a + b;
}
// one-line function. Sucre syntaxique pour les fonctions qui retournent une expression
int addVerion2(int a, int b) => a + b;
Console.WriteLine(add(10, 12));
Console.WriteLine(addVerion2(10, 5));
using System;
var r = new Random();
int x = r.Next(100);
Console.WriteLine(x);
// une expression tout ce qui renvoie une valeur
// exemples: 10, x + 5, x == 100, r.Next(100), x = 10
// expression booléenne: tout ce qui renvoie un booléen
// if prend une expression booléenne
if (x > 50)
{
Console.WriteLine("Above");
}
else
{
Console.WriteLine("Below");
}
switch (x)
{
case 0:
Console.WriteLine("Zero");
break;
case 2:
case 3:
Console.WriteLine("Two or three");
break;
case 50:
Console.WriteLine("Average");
break;
default:
Console.WriteLine("default");
break;
}
var s = "hello";
switch (s)
{
case "hello":
Console.WriteLine("Zero");
break;
case "salut":
Console.WriteLine("Two or three");
break;
default:
Console.WriteLine("default");
break;
}
int test = s switch
{
"hello" => 100,
null => 0,
_ => -200,
};
// pattern matching: permet d'avoir des embrachements ou des condidions sophistiqués
// accessible principalement avec "is"
int? i = 12;
if (i is not null)
{
Console.WriteLine(i);
}
object y = 15;
if (y is string text) // vérifir que c'est une string et cast y dans text en string
{
Console.WriteLine($"{text} is a string");
}
else if (y is int z)
{
Console.WriteLine($"{z} is an int");
}
static bool IsFirstSummerMonday(DateTime date) => date is { Month: 6, Day: <= 7, DayOfWeek: DayOfWeek.Monday };
static bool IsFirstSummerMonday2(DateTime date) => date.Month == 6 && date.Day <= 7 && date.DayOfWeek == DayOfWeek.Monday;
static bool IsLetter(char c) => (c is >= 'a' and <= 'z') or (>= 'A' and <= 'Z');
// (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
DateTime d = DateTime.Now;
switch (d)
{
case { Month: 6, Day: <= 7, DayOfWeek: DayOfWeek.Monday }:
Console.WriteLine("monday");
break;
case { Month: 6, Day: <= 7, DayOfWeek: DayOfWeek.Thursday }:
Console.WriteLine("jeudi");
break;
case { Month: <= 6, Day: >= 7, DayOfWeek: DayOfWeek.Wednesday }:
Console.WriteLine("Le mercredi c'est permis");
break;
default:
break;
}
using System;
// espace de noms / équivalent à un package java
namespace hugo.fournier
{
// Historiquement, toute fonctione doit être dans une classe
class Toto
{
// point d'entrée
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
using System;
// depuis c#9, le point d'entée peut être la première ligne de code
Console.WriteLine("Hello World!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment