Why write O AS INT and not write (INT) O

I found in Jon Skeet's book an example of use as a type operator that allows null .

using System;

class A
{
    static void PrintValueAsInt32(object o)
    {
        int? nullable = o as int?; // can't write int? nullable = (int?)o
        Console.WriteLine(nullable.HasValue ?
                          nullable.Value.ToString() :
                          "null");
    }

    static void Main()
    {
        PrintValueAsInt32(5);
        PrintValueAsInt32("some string");
    }
}

I can’t understand why I can’t write int? nullable = (int?)o? When I try to do this, I get an exception.

+4
source share
1 answer

Since it as operatorchecks before casting. If the types are not converted to each other, then it just returns null and avoids InvalidCastException.

You get an exception when you try to perform an explicit cast, because in the second call you pass the string to a method that does not convert to int?

+14
source

Source: https://habr.com/ru/post/1538139/


All Articles