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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With