Monday, January 30, 2012

Best Extension Methods: Convert To Integer

below extension methods converts an object/double/string to integer and if its not convertable then returns 0.

 public static int ToInt(this object source)
    {
        int val = 0;
        if (source != null)
        {
            string str = Convert.ToString(source);
            if (!string.IsNullOrEmpty(str))
            {                
                int.TryParse(str, out val);
                if (val <= 0)
                {
                    try
                    {

                        val = (int)Convert.ToDouble(str);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        return val;
    }

Compiled By: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates