Tuesday, July 17, 2007

erroneous InvalidCastException


todays puzzler may be hard to read in the screen shot above (click on image to expand) but basically the debugger is complaining that I'm trying to cast the value "0" to an integer value and it can't handle that. (fwiw, most people accept zero as a valid integer)... bizarre!

if ((int)Args.NewValues["ItemPrice"] < 0)
{
Args.Cancel = true;
EditMSG.Text = "-- Item price is out of range";
}

can anyone tell me why the if statement bombs when Args.NewValues["ItemPrice"] == "0"? I should think that would cast nicely to an int as I am attempting. (BTW Args is type DetailsViewUpdateEventArgs)

UPDATE:
here's a workaround --
if (Convert.ToInt32(Args.NewValues["ItemPrice"]) < 0)...

this way you're not casting, you're converting. ok!

1 comment:

said...

This is because your "0" value is not an int in memory; it's a string. This is the sort of thing that might "magically" get handled by some scripting languages, but it isn't Kosher for Java, C, and .NET. By all accounts, this is exactly the sort of situation where you ought to get an InvalidCastException. You are attempting to tell the compiler that a string is an int, which it is not.

Are you complaining that casting doesn't imply an attempt at conversion, or do you not understand the basics of data types?

About Me

My photo
smug SoCal catalyst prone to puffery. practitioner of verbal aikido. pearl caster for swine. professional. intuitive. clean. approachable. unique. forgiven sinner. ubiquitous. reads. geekiness rating ~10%. Meyers-Briggs = iNTj. musical thinker. into nature. project manager for a decent place which gives plenty of time, money and chances to prove his talent. dabbler, a dilettante, jack of all trades, master of none. lives in a nice place with a great wife and kids. his boys and attitude keeps him young. hangs out a lot, never bored. listens to XM. doesn't do favorites. tries to play the blues on acoustic guitar. loves the beach. draws. chillz' an groovz'. smokes a pipe. lefty.