I am curious about why the .NET TryParse methods (e.g. Int32.TryParse, DateTime.TryParse) do not accept an Object and instead accept a String for the first argument containing the number to be parsed. If I'm using TryParse, I'm keeping in mind that the method may fail and I'm using it for convenience. I would be fine with TryParse silently failing on the object and populating my result with 0 and returning false.
1 Answer
What reason would a .NET Framework designer give me for making the first argument
String?
Well you'd have to ask a .NET Framework designer instead of the community at Stack Overflow, but I'll take a crack.
The code only deals with
strings.Accepting an
objectand checking if it was astringwould impose a performance penalty on everybody else using the function correctly.Types like
Action<Guid>can never meaningfully represent a number so usingstringinstead ofobjectmakes calling the function with a meaningless type impossible (i.e. what result other thanfalsecould it possibly be? Save yourself the function call.)You can emulate
TryParseyourself with arbitraryobjects usingtry/catchandConvert.ToInt32(object).It doesn't solve any problem.
2 Comments
Convert.ToString(string) is a good one. Presumably included for symmetry.
ToStringon their arguments, but that seems like not much help.Convert.ToInt32(object)exists (as do a lot ofToSomeType(object)functions) but they don't come in aTry*form.TryParsewith aGuidand have it return false, of course!