In C#, can value be extracted using AS keyword? How?

58 Views Asked by At

I have written the following code :

        object obj = 123; // Line 1
        int? num = null; // Line 2
        num = obj as int; // Line 3

I am getting compile time error in Line 3 as - "the as keyword must be used with reference type or nullable type('int' is a non-nullable value type)".

I want to understand:
1. Though my int is nullable, why then is it giving this error
2. How can we get the value of obj in num? Won't AS keyword work here?

2

There are 2 best solutions below

0
On

Int? And int are two different types.

Change

    num = obj as int; // Line 

To

   num = obj as int?;

for readability, you may even write:

 Nullable<int> num;
 num = obj as Nullable<int>;

I'm going to extend this a little more and say, how do you get the value from a nullable object. Well, here's one way.

object obj = 123;
int? num;
num = obj as int?;
int myNumericValue = default(int);
If (num.HasValue) myNumericValue = num.Value;
0
On

In order for this to work....

num = obj as int; // Line 3

...the as operator must be able to return null if obj cannot be cast to int. But int cannot store a null, so it results in an error.

You have two alternatives:

1. Use nullable int

int? num;
num = obj as int?;

2. Use a little more code

int num;
num = (obj is int) ? (int)obj : default(int);