3

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?

9
  • Is using an extension method out of the question to use TryParse? Commented Aug 8, 2016 at 13:55
  • definitely an extension method Commented Aug 8, 2016 at 13:56
  • @ScottKaye - I've never used extension methods. Googling around to see how to use them and I'll give it a shot. Commented Aug 8, 2016 at 13:57
  • 1
    @ScottKaye Since the is being injected into code I doubt that an extension method could be used. Commented Aug 8, 2016 at 13:59
  • 2
    Possible duplicate of How do I identify if a string is a number? Commented Aug 8, 2016 at 14:11

3 Answers 3

11

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..
}
Sign up to request clarification or add additional context in comments.

6 Comments

Doesn't handle long numeric numbers, nor does it handle comma/period delimiters.
This answers the question, but using @this as a parameter name is a very, very bad choice. Not to mention using it as an extension method parameter. Personally i find using keywords as parameter and variable names as something to be avoided.
@user3185569 - You might be right regarding the parameter name. I changed it to input. Personally I find @this very logical in this (pun not intended) particular case just because it shows what your extension is extending. But that's just me.
@AgentFire - Yes, in that case you might want to use Int64.TryParse, but I understood the OP as int.TryParse could be used, but not in a single line.
return int.TryParse(input, out int number); saves 1 line.
|
4

In response to this:

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?

You guys don't have to make it account for anything more complicated than a positive integer.

new Regex(@"^\d{4}").IsMatch("3466") // true
new Regex(@"^\d{4}").IsMatch("6")    // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg") // true

// in an if:
if (new Regex(@"^\d{4}").IsMatch("3466"))
{
    // Do something
}

Old answer:

If you can't use TryParse, you could probably get away with using LINQ:

"12345".All(char.IsDigit); // true
"abcde".All(char.IsDigit); // false
"abc123".All(char.IsDigit); // false

If you can, here's an IsNumeric extension method, with usage:

public static class NumberExtensions
{
    // <= C#6
    public static bool IsNumeric(this string str)
    {
        float f;
        return float.TryParse(str, out f);
    }

    // C# 7+
    public static bool IsNumeric(this string str) => float.TryParse(str, out var _);
}

// ... elsewhere

"123".IsNumeric();     // true
"abc".IsNumeric();     // false, etc
"-1.7e5".IsNumeric();  // true

8 Comments

problem is this doesn't !00% verify it's an int
@Jonesopolis True, it's a workaround for sure. The extension method approach is better, but if OP is just after a basic "string only contains numbers" method, it should work.
@AgentFire Neither does int.TryParse. I'll update to use float.TryParse for the extension method. This problem could be solved in a lot of ways (including regex), the "best" solution just depends on what the OP needs.
You guys don't have to make it account for anything more complicated than a positive integer. I'll update the question to be more specific about this.
"".All(char.IsDigit); returns "TRUE"
|
3

How about some easy LinQ?

if (str.Take(4).All(char.IsDigit) { ... }

1 Comment

What about negatives and decimals?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.