I had some useful extension for string
s. 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:
static void ConversionTest()
{
string strItems = null;
strItems = "0";
int intItem;
if (int.TryParse(strItems, out intItem))
{
if (intItem < 1)
Console.WriteLine("Please enter valid value.");
}
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);
}
public static int? ToInt(this string text)
{
int num;
return int.TryParse(text, out num) ? num : (int?)null;
}
public static int ToInt(this string text,int defaultVal)
{
int num;
return int.TryParse(text, out num) ? num : defaultVal;
}
public static string StringFormat(this string text, params object[] formatArgs)
{
return string.Format(text, formatArgs);
}
}
Another useful Extension method.
Returns whether
DataSet
contains some
DataRow
s or not.
public static class DataSetExtensions
{
public static bool IsNullOrEmpty(this DataSet ds)
{
return (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0);
}
}