This commit is contained in:
Smaug123
2025-06-27 12:09:15 +01:00
parent c049313dd9
commit 277f303431
4 changed files with 47 additions and 7 deletions

View File

@@ -14,8 +14,11 @@ public class Program
{
Bird sparrow = new Bird { CanFly = true };
// This should fail and return null (not throw)
Fish fish = sparrow as Fish;
// Cast to object first to bypass compile-time checking
object obj = sparrow;
// This should fail at runtime and return null (not throw)
Fish fish = obj as Fish;
return fish == null ? 42 : 0;
}

View File

@@ -0,0 +1,30 @@
public class Program
{
public interface IAnimal
{
string Name { get; set; }
}
public class Bird : IAnimal
{
public string Name { get; set; }
public bool CanFly { get; set; }
}
public class Fish : IAnimal
{
public string Name { get; set; }
public bool CanSwim { get; set; }
}
public static int Main(string[] args)
{
IAnimal animal = new Bird { Name = "Sparrow", CanFly = true };
// This should fail at runtime and return null (not throw)
// because the actual object is Bird, not Fish
Fish fish = animal as Fish;
return fish == null ? 42 : 0;
}
}