John V
John V

Reputation: 5047

Can I invoke casting error when casting int types?

it is a bit unusual question but I am unable to get casting error when casting numeric types. I would need to get some error like "value too short" etc. but seems that C# guards it quite well. Could you provide me with a simple code that fails on casting? (like stackoverflow..)

Upvotes: 0

Views: 61

Answers (3)

HatSoft
HatSoft

Reputation: 11201

Could you provide me with a simple code that fails on casting?

int i = 400;
object o = i; // here o will be System.Int32 automatically

string s = (string)o; //Runtime Exception thrown System.InvalidCastException:

Upvotes: 0

Lee
Lee

Reputation: 144196

You can use the checked keyword to explicitly check for overflow of integral type conversions:

int i = int.MaxValue;
short s = checked((short)i);

There is also a checked compiler flag which can make checked conversions the default.

Upvotes: 4

Brad Rem
Brad Rem

Reputation: 6026

It sounds like you are trying to write some error handling code. The compiler does do a great job of watching for inappropriate casts, but if you're looking for a runtime exception:

short y = short.Parse("56789");

This will throw an OverflowException.

OverflowException: Value was either too large or too small for an Int16.

Upvotes: 0

Related Questions