65.9K
CodeProject is changing. Read more.
Home

Basic string to integer conversion extensions

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (3 votes)

Jun 14, 2011

CPOL
viewsIcon

23608

String handling Extension Methods

I had some useful extension for strings. When I read this article Handy Extension Methods, I thought I'd share them.

In one of my projects, I had to validate a lot of TextBox values (e.g., value of TextBox txtItemSupplied must be an integer with value greater than 0).

I had written some basic extension methods for string to integer conversions. The methods were used for validating input data.

Here is the code:

//validation strItems must be greater then 0.
static void ConversionTest()
{
    string strItems = null;//test input
    strItems = "0";//test input
    //previous check for integer greater then 0.
    int intItem;
    if (int.TryParse(strItems, out intItem))
    {
        if (intItem < 1)
            Console.WriteLine("Please enter valid value.");
    }
    //New check for integer greater then 0.
    if (strItems.ToInt(0) < 1)
    {
        Console.WriteLine("Please enter valid value.");
    }
}

Now this is the Extension class:

public static class MyStringExtensions
{
    public static bool IsInt(this string text)
    {
        int num;
        return int.TryParse(text, out num);
    }
    //get null if conversion failed
    public static int? ToInt(this string text)
    {
        int num;
        return int.TryParse(text, out num) ? num : (int?)null;
    }
    //get default value if conversion failed
    public static int ToInt(this string text,int defaultVal)
    {
        int num;
        return int.TryParse(text, out num) ? num : defaultVal;
    }

    //formating a string
    public static string StringFormat(this string text, params object[] formatArgs)
    {
        return string.Format(text, formatArgs);
    }


}

Another useful Extension method. Returns whether DataSet contains some DataRows or not.
public static class DataSetExtensions
    {
    //Return whether DataSet contains DataRow(s) or not
        public static bool IsNullOrEmpty(this DataSet ds)
        {
            return (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0);
        }
    }