Reputation: 2151
I am just curious to know why the C# language team has not provided a IsNumeric function on the String object?. IsNumeric function would have been more proper on a String object that the Int32.TryParse Function.
Note: I am asking this question because I have found it difficult to explain this to a beginner and I don't like them cursing C# for this!
Update: Please, this question is not about how to Implement a IsNumeric function.
Upvotes: 5
Views: 3585
Reputation: 176219
I think the logic behind Int32.TryParse
is that the Int32
class knows what is a valid 32-bit integer whereas the String
class has no notion of what is a number at all.
The principle behind that is that an object can best check itself whether something can be treated as/converted to that specific object.
Upvotes: 3
Reputation: 21727
On a side-note: You can always implement your own:
public static class StringExtensions
{
public static Boolean IsNumeric(this String s)
{
// your own definition goes here
}
}
Upvotes: 0
Reputation: 8038
IIRC there ist Char.IsDigit(char c);
Therefore I think that should work:
string _temp = "12341234";
bool _isNumeric = _temp.ToCharArray().All(x => Char.IsDigit(x));
And you could wrap that as an extension methods if you like.
Upvotes: 1
Reputation: 49502
The trouble with a method like that would be deciding what counts as "numeric". Should it allow decimals points, should it allow leading whitespace, should it have an upper bound for the number of digits?
Int32.TryParse answers the much more well-defined question of, "is this a valid string representation of an Int32?"
And of course, nothing is stopping you writing your own extension method, that decides if a string is numeric according to your own rules.
Upvotes: 17
Reputation: 28060
There has to be a line somewhere, between the methods you put into a class and the operations that are better performed by other classes.
If there was a IsNumeric method, other people might ask for a IsValidPhoneNumber, IsValidEmailAddress, IsValidURI or even IsValidZipCodeInNewZealand methods... all of those might better be implemented in their own domain.
Upvotes: 3
Reputation:
Because there can be a ton of functions one can find useful and absolutely needed.
IsNumeric()
IsAlpha()
IsAlphaNumeric()
IsEmailAddress()
IsGuid()
...
And so on. Any individual can easily add a dozen more methods that he would consider as absolutely needed. A framework is only meant to stay generic and provide the basic tools for you to do your work and maybe to build your extra tools as needed.
That said, simply add your extension methods.
Upvotes: 4