1

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.

7
  • 1
    What reason would a .NET Framework designer give me for making the first argument String Because the code only deals with strings. You're basically asking why do we bother typing our parameters at all? Commented Jul 31, 2013 at 5:21
  • 2
    These methods are intended to translate string representing integers and dates, into integers and dates. Sure, they could provide sugar overrides that simply call ToString on their arguments, but that seems like not much help. Commented Jul 31, 2013 at 5:24
  • And for what it's worth, Convert.ToInt32(object) exists (as do a lot of ToSomeType(object) functions) but they don't come in a Try* form. Commented Jul 31, 2013 at 5:27
  • @cbp Because then I could call TryParse with a Guid and have it return false, of course! Commented Jul 31, 2013 at 5:29
  • I would like to call .ToString, but that could fail since I don't know the underlying type. Well whoever implemented the underlying type is a bad programmer. msdn.microsoft.com/en-us/library/system.object.tostring.aspx Your ToString override should not throw an exception. Commented Jul 31, 2013 at 5:36

1 Answer 1

5

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.

  1. The code only deals with strings.

  2. Accepting an object and checking if it was a string would impose a performance penalty on everybody else using the function correctly.

  3. Types like Action<Guid> can never meaningfully represent a number so using string instead of object makes calling the function with a meaningless type impossible (i.e. what result other than false could it possibly be? Save yourself the function call.)

  4. You can emulate TryParse yourself with arbitrary objects using try/catch and Convert.ToInt32(object).

  5. It doesn't solve any problem.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Item 5 should actually be on top of the list. It's THE argument: It simply doesn't solve any problem.
As far as curiosities go, Convert.ToString(string) is a good one. Presumably included for symmetry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.