Aller au contenu

Opérateurs is et as

Contexte : is vérifie si un objet est compatible avec un type donné ; as effectue un cast sécurisé (retourne null si incompatible).

object obj = "Bonjour";
if (obj is string s)
{
Console.WriteLine($"Longueur: {s.Length}");
}
object obj = "Bonjour";
string str = obj as string;
if (str != null) Console.WriteLine(str.Length);