开发者

Is this extension method to force a string into an integer or default to 0 redundant?

I needed a one-liner to convert a string to an integer, and if the string is anything invalid, then just set it to zero. So I made the following extension method, but I can imagine there is a system method to do this in one line.

Is there another way to do this in one line without creating an extension method?

using System;

namespace TestForceInteger
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Wr开发者_运维技巧iteLine("testing".ForceInteger() + 1);
            Console.WriteLine("199".ForceInteger() + 1);
            int test = StringHelpers.ForceInteger(null);
            Console.WriteLine(test + 1);
            Console.ReadLine();
            //output:
            //1
            //200
            //1
        }
    }

    public static class StringHelpers
    {
        public static int ForceInteger(this string potentialInteger)
        {
            int result;
            if (int.TryParse(potentialInteger, out result))
                return result;
            else
                return 0;
        }
    }
}


Not as a one-liner, afaik, but if you want to avoid the extension method you can initialize the result to 0 and ignore the outcome of TryParse:

int result = 0;
int.TryParse(potentialInteger, out result)


Not a conventional way with the framework libraries, no.

Your extension method would be better if it returned a nullable int, so that you could distinguish between "invalid" and 0.


Don't code for simplicity of writing your code, code to the specification. It makes far more sense to create a method that actually does the job properly and notes the difference between an invalid conversion and a magic number. When you make this method, you need only make it once, so do it properly. In the layer above it you can then do the conversion you require to whatever system you are using.

I.e.:

public static class Extensions
{
    public static int? ReturnIntegerIfValid(this string potentialInteger)
    {
        try
        {
            int result;

            if (int.TryParse(potentialInteger, out result))
            {
                return result;
            }
            else
            {
                return null;
            }
        }
        catch (ArgumentException)
        {
            return null;
        }
    }
}


Use

int result;
result = Int32.TryParse(potentialInteger, out result) ? result : 0; // or default(int)

to ensure setting to 0. But this is absolutely unnecessary (see @Anthony's comment to @Paolo's answer)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜