Check if string is numeric in one line of code

TheIronCheek picture TheIronCheek · Aug 8, 2016 · Viewed 27.1k times · Source

I'm working with a DNN form-building module that allows for some server-side code to be run based on a condition. For my particular scenario, I need my block of code to run if the first 4 characters of a certain form text are numeric.

The space to type the condition, though, is only one line and I believe gets injected into an if statement somewhere behind the scenes so I don't have the ability to write a mult-line conditional.

If I have a form field called MyField, I might create a simple conditional like this:

[MyField] == "some value"

Then somewhere behind the scenes it gets translated to something like if("some value" == "some value") {

I know that int.TryParse() can be used to determine whether or not a string is numeric but every implementation I've seen requires two lines of code, the first to declare a variable to contain the converted integer and the second to run the actual function.

Is there a way to check to see if the first 4 characters of a string are numeric in just one line that can exist inside an if statement?

Answer

smoksnes picture smoksnes · Aug 8, 2016

Wrap it in an extension method.

public static class StringExtensions
{
    public static bool IsNumeric(this string input)
    {
        int number;
        return int.TryParse(input, out number);
    }
}

And use it like

if("1234".IsNumeric())
{
    // Do stuff..
}

UPDATE since question changed:

public static class StringExtensions
{
    public static bool FirstFourAreNumeric(this string input)
    {
        int number;
        if(string.IsNullOrEmpty(input) || input.Length < 4)
        {
            throw new Exception("Not 4 chars long");
        }

        return int.TryParse(input.Substring(4), out number);
    }
}

And use it like

if("1234abc".FirstFourAreNumeric())
{
    // Do stuff..
}