Archive

Posts Tagged ‘Convert’

Parse or Convert?

September 17th, 2003

I was sifting through some code a co-worker of mine wrote this morning and noticed that they were handling the conversion of request params differently than I had in the past and so of course I was interested in knowing which approach was right (read: make sure all my previous code isn’t going to blow up). The specific issue here is in converting values in the Request.Params collection that are expected to be integers. In the past I have always handled this in the following manner:

int val = Convert.ToInt32(Request.Params["val"]);

 
Seemed simple enough with no apparent problems right? Well my co-workers code looked like this:

int val;
val = Request["val"] == null ? 0 : Int32.Parse( Request["val"] );

 
So my interest was peaked; what are the differences and the pros and cons between Parse vs. Convert? Which one is better? Does it even matter? In short – it really doesn’t matter which one you choose for the most part. However, there is an interesting difference between the two, and that is in how they handle null values. Convert will do all it can in it’s power to change what you passed in to the thing you ultimately asked for, so it will check for a null and upon finding one will simply return 0. Int32.Parse on the other hand is a little more sensitive in that it expects a valid integer value from the caller and will throw and exception when you pass in null. This all seems harmless until you add a little context.

If we look again at the second example we now realize that this could be done a lot more efficiently (in terms of simplicity) by using Convert instead of Parse because we can rely on Convert to do the null check for us. The end result would give us code that looks just like the first example.

However, if we consider the first example we need to be cognizant of the fact that we will get 0 when we pass in null using Convert. Seems harmless, but in many cases (as was mine) you’re going to be using that integer in a context where 0 is valid apart from null. Take for example looking up some record from the database based on how that integer gets converted. 0 could be a valid record id which would then cause the code to execute on an unexpected record. Say you were processing a delete request and the id of the record in question is being stored in cache/session. If the cache/session expires before you execute this request it will errantly delete the wrong record. There are countless other potential problems along these same lines if you don’t make sure that nulls are handled in a way consistent with your logic.

So in summary, if you want to protect from invalid integers being passed in and therefore have a higher reliability of data integrity, then you should use Parse. However, if your looking for an easy way to handle nulls and remain aware that these will become 0 then Convert is an easy way to avoid having to check for yourself.

.NET, Programming , ,