Another simple use of extension methods!!

While my team and I doing our daily work. One of our new team members asked that he needs the user to select a value from drop-down list and this value should be converted to a nullable integer value.

The small issue he faces that he need to parse the value selected in one line of code and make sure that if the user does not select a value the default value will be parsed to null and do not cause a problem -in each drop-down there is a "[Select]" item with empty string value  -

I wondered a int.Parse function returns null when the parsed value is null  but throws  "Input string was not in a correct format" exception when try to parse an empty string. And when use int.TryParse  it will result with 0 value when parsing operation failed.

In such simple scenario extension methods proof it self. Simply we can create an extension method call it SafeParse for example ....

public static int? SafeParse(this String Value)
   
{
       
if (string.IsNullOrEmpty(Value))
           
return null;
       
else
           
return int.Parse(Value);
   
} 
 
and then you could simply use it like this:
 
int? MyNullableValue;
MyNullableValue = DropDownList1.SelectedValue.SafeParse();
 
Extension methods provide a simple and easy use which will ease programmer day day work, and make simple issues disappear just like 1,2,3 
 
Thanks for VS2008,thanks for extension methods, thanks for Microsoft team
 
Happy programming...!!

7 Comments

  • TryParse returns false if it can't be parsed, so you can detect the difference between that and the value just being 0. TryParse also covers other reasons it can't be parsed -- your code will still throw if you pass it 'a' for example.

  • public static int? SafeParse(this String Value)
    {
    try
    {
    int x;
    x = int.Parse(Value);
    return x;
    }
    catch (Exception)
    {
    return null;
    }
    }

  • I think above actual one is better as it is not using try catch.
    I think it is the rule of the thumb to not use try catch if u know the problem and try to solve it via a proper handling

  • int i;

    if(int.TryParse("text",out i))
    {
    // do something
    }

    is much more elegant and it also comes standard with the .NET framework. It also covers much more then your method as InfinitiesLoop mentioned.

  • First, Thanks for comments and concern
    "And when use int.TryParse it will result with 0 value when parsing operation failed." As you know TryParse takes 2 parameters the value an out parameter called "result" this parameter which will be returned 0 when TryParse failed. And I meant it's safe for parsing empty strings not safe to parse non numeric strings. I hope that clear for you.

  • I'd rather:

    public static int? SafeParse(this String Value) {
        int i;
        return int.TryParse(Value, out i)? i : null;
    }

  • 5TnNia Really appreciate you sharing this blog article. Want more.

Comments have been disabled for this content.