0

I have many functions that have optional parameters with the default value as null such as this:

public static IEnumerable<Product> GetProducts(int? productCategoryId = null)

In my linq where clause I usually like checking if like this:

if (productCategoryId == null || productCategoryId == p.ProductCategoryId)

In my application I usually have to pass selected values that come from a Telerik ComboBox into functions like this so a list of products can be filtered down:

GetProducts(CategoryComboBox.SelectedValue);

C# will not allow me to do this because if the user doesn't select anything in the ComboBox the selected value is an empty string which will not work with my function since I prefer sending in NULL if there is no selection, otherwise the id of whatever they selected.

Any recommendations on a good extension method for this or if C# / Telerik ComboBox has a built in function for this? Here is what I currently have:

    public static int? ToNullableInt32(this string val)
    {
        int i;
        if (Int32.TryParse(val, out i)) return i;
        return null;
    }

In the example above I also need to get it to return a nullable int as null or the selected value as an int.

4
  • sorry typed this fast meant to put int? I updated it now Commented May 5, 2015 at 12:26
  • What you have looks ok to me, although I personally would not make it an extension method (just a static method of some static utility class). Commented May 5, 2015 at 12:28
  • Alright, is there any rule of thumb you follow for when to make it an extension method vs not? Commented May 5, 2015 at 12:36
  • 1
    Well, anything that adds behaviour to primitive types is a bit suspect, unless it is intrinsically related. For example, adding a string.Left() method would be ok, since the concept of returning the leftmost N characters of a string is intrinsically a string operation. However, converting a string to a nullable int is not. Commented May 5, 2015 at 13:59

1 Answer 1

0

This is a fantastic solution that uses a generics. We use it all over our codebase.

Generic TryParse Extension method

once you have that, then you can do...

this.GetProducts(this.CategoryComboBox.SelectedValue.TryParse<int>());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.