repl.it
@kenanhancer/

SafelyCasting

C#

No description

fork
loading
Files
  • main.cs
  • main.exe
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;

class MainClass {
  public static void Main(string[] args)
  {
    Giraffe g = new Giraffe();
    FeedMammals(g);

    TestForMammals(g);

    SuperNova sn = new SuperNova();
    TestForMammals(sn);
  }

  static void FeedMammals(Animal a)
  {
    // Use the is operator to verify the type
    // before performing a cast.
    if (a is Mammal m)
    {
        m.Eat();
    }
  }

  static void TestForMammals(object o)
  {
    // Alternatively, use the as operator and test for null
    // before referencing the variable.
    if (o is Mammal m)
    {
        Console.WriteLine(m.ToString());
    }
    else
    {
        // variable 'm' is not in scope here, and can't be used.
        Console.WriteLine($"{o.GetType().Name} is not a Mammal");
    }
  }
}

class Animal
{
    public void Eat() { Console.WriteLine("Eating."); }
    public override string ToString()
    {
        return "I am an animal.";
    }
}

class Mammal : Animal { }
class Giraffe : Mammal { }

class SuperNova { }
?