static void Str_IsAndAs_1() { Griaffe g = new Griaffe(); FeedMammals(g); SuperNova sn = new SuperNova(); TestForMammals(sn); void FeedMammals(Animal a) { if (a is Mammal m) { m.Eat(); } } void TestForMammals(object o) { if (o is Mammal m) { Console.WriteLine(m.ToString()); } else { Console.WriteLine($"{o.GetType().Name} is not a Mammal "); } } }
static void Str_IsAndAs_3() { { // Use the is operator to verify the type. // before performing a cast. Griaffe g = new Griaffe(); UseIsOperator(g); // Use the as operator and test for null // before referencing the variable. UseAsOperator(g); // Use the as operator to test // an incompatible type. SuperNova sn = new SuperNova(); UseAsOperator(sn); // Use the as operator with a value type. // Note the implicit conversion to int? in // the method body. int i = 5; UseAsWithNullable(i); double d = 9.78654; UseAsWithNullable(d); } void UseIsOperator(Animal a) { if (a is Mammal) { Mammal m = (Mammal)a; m.Eat(); } } void UsePatternMatchingIs(Animal a) { if (a is Mammal m) { m.Eat(); } } void UseAsOperator(object o) { Mammal m = o as Mammal; if (m != null) { Console.WriteLine(m.ToString()); } else { Console.WriteLine($"{o.GetType().Name} is not a Mammal"); } } void UseAsWithNullable(System.ValueType val) { int?j = val as int?; if (j != null) { Console.WriteLine(j); } else { Console.WriteLine("Could not convert " + val.ToString()); } } }