repl.it
@kenanhancer/

CastingAndTypeConversion

C#

Implicit and explicit conversion

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
using System;

class MainClass {
  public static void Main (string[] args) {
    
    // Implicit conversion. A long can
    // hold any value an int can hold, and more!
    int num = 2147483647;
    long bigNum = num;


    double x = 1234.7;
    int a;
    // Cast double to int.
    a = (int)x;
    System.Console.WriteLine(a);

    Derived d = new Derived();
    Base b = d; // Always OK.

    // Create a new derived type.
    Giraffe g = new Giraffe();
      
    // Implicit conversion to base type is safe.
    Animal a = g;
      
    // Explicit conversion is required to cast back
    // to derived type. Note: This will compile but will
    // throw an exception at run time if the right-side
    // object is not in fact a Giraffe.
    Giraffe g2 = (Giraffe) a;


  }
}

class Base {}

class Derived : Base {}

class Animal {}

class Giraffe : Animal {}
?