I find myself often needing to use int.TryParse() to test if a value is an integer. However, when using TryParse, I have to pass a reference variable to the function. So I find myself always needing to create a temp int to be passed in. Usually it looks something like:
int my_temp_integer;
int.TryParse(potential_integer, my_temp_integer);
I find this to be quite cumbersome considering that all I want is a simple true/false response, and I don’t care about the actual parsed result. Is there a better way to approach this? Why isn’t there an overloaded function where I can just pass the value I want to test and get a true/false response?
Thanks.
you could write an extension method:
then your example becomes:
EDIT:
Lately I have been using a generic form of this.
Can then use it as follows; it’s not perfect, but it’s more concise than anything I’ve found:
Theoretically, this would also work with custom
TryParsemethods, as long as you followed the same pattern as the official ones.Update: If you maintain a static dictionary of
TryParsemethods by type, you can avoid having to ever directly pass the method. The dictionary can even be populated as needed with reflection.