Skye Lewis
Skye Lewis

Reputation: 51

Dictionary issue

I have a Dictionary defined as Dictionary (string, object). I'm accessing other values (strings) in the dictionary without issue, but when I try to access an 'int' I'm getting an issue. When I try and compile this:

            int score = obj["score"] as int;

I get the error: 'The 'as' operator cannot be used with a non-nullable value type 'int'

More than happy to stick my head int the sand, I recoded it to this:

        int score = (int) obj["score"];

...it does compile but at run time I receive this error:

InvalidCastException: Cannot cast from source type to destination type.

Can anyone tell me where I'm going wrong?

Upvotes: 0

Views: 445

Answers (4)

cdie
cdie

Reputation: 4544

Do this way :

 int score = Convert.ToInt32(obj["score"]);

Upvotes: 0

asawyer
asawyer

Reputation: 17808

http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.90).aspx

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception

Int32 is not a nullable type, so as cannot be applied to it.

int score = obj["score"] as int? ?? 0;

This would work, notice it is casting to Nullable<int> and then coalesing to 0 if the cast fails.

Upvotes: 2

Adam Sears
Adam Sears

Reputation: 355

You can also just simply use Convert.ToInt32(value), Int32.Parse(), or Int32.TryParse [as bland suggested]. All of those should work.

Upvotes: 0

bland
bland

Reputation: 2004

Assuming your value is a string:

int score = -1;
int.TryParse(obj["score"], out score);

You must parse the integer from the string.

Upvotes: 0

Related Questions