C# and ConvertToNullable

Time to time, we need to convert values to another variable type. For example, when we save the product price, we need to convert string value to numeric value that is entered from user interface. Also, time to time we need to convert value to null value and save it as a null. For example, user creates a product from user interface but there is no discount value for this product. And we want to save discount value as a null.

For this kind of cases, every time we create different and lot of if conditions. Finally, i have created a ConvertToNullable functions for myself. Here is the simple ConvertToNullable function to convert object to nullable integer.

    public static Nullable<Int32> ConvertToNullableInt32(string value)
    {
        Nullable<Int32> convertedValue = null;
        if (!string.IsNullOrEmpty(value))
        {
            Int32 converted = 0;
            if (Int32.TryParse(value.ToString(), out converted))
            {
                convertedValue = converted;
            }
        }
        return convertedValue;
    }

you can extend or create similar functions for your needs.

0 comments:

Post a Comment