Integer.TryParse - a better way?

2019-01-17 03:39发布

I find myself often needing to use Integer.TryParse to test if a value is an integer. However, when you use TryParse, you have to pass a reference variable to the function, so I find myself always needing to create a blank integer to pass in. Usually it looks something like:

Dim tempInt as Integer
If Integer.TryParse(myInt, tempInt) Then

I find this to be quite cumbersome considering that all I want is a simple True / False response. 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?

7条回答
时光不老,我们不散
2楼-- · 2019-01-17 04:08

Why not write an extension method to clean up your code? I haven't written VB.Net for a while, but here is an example in c#:

public static class MyIntExtensionClass
{
  public static bool IsInteger(this string value)
  {
    if(string.IsNullOrEmpty(value))
      return false;

    int dummy;
    return int.TryParse(value, dummy);
  }
}
查看更多
登录 后发表回答