p e p
p e p

Reputation: 6674

Why doesn't TryParse accept an Object?

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.

Upvotes: 1

Views: 164

Answers (1)

ta.speot.is
ta.speot.is

Reputation: 27214

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.

Upvotes: 5

Related Questions