Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must write O AS INT and can't write (INT)O

Tags:

c#

I've found in the Jon Skeet's book an example of using as operator with the types, which allows null value.

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 that, I'm getting an exception.

like image 370
Dima Kozyr Avatar asked Dec 09 '22 08:12

Dima Kozyr


1 Answers

Because the as operator is performing a check before cast.If types are not convertible to each other then it just returns null and avoids the InvalidCastException.

You are getting an exception when you try to perfom explicit cast because in the second call you are passing a string to the method which is not convertible to int?

like image 132
Selman Genç Avatar answered Dec 11 '22 07:12

Selman Genç