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