Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Basic string to integer conversion extensions

4.17/5 (3 votes)
21 Jun 2011CPOL 23.6K  
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:


C#
//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:


C#
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.

C#
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);
        }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)