Are nullable types ideal for my situation?

Recently converted my ASP.NET project from 1.1 to 3.5. Hooray! We are currently developing a form that contains several optional fields. I usually go through my code adding a ton of if statements, checking for an empty field, and setting the value to 0 if so. So I'm wondering if it would be better to declare private variables with a null value for each of these fields instead, and then add them as parameters for my database update? Using MSSQLS 2000, already set the appropriate fields to allow null.

To clarify, the web form has fields for the dollar amount. The default value for inputs is 0, but if the user removes one of those 0s, leaving the field blank, he submits the form, an exception will be passed to Convert.ToDecimal (MoneyField.Text) in the argument list of the method that submits the whole thing to the database. Is there a cleaner way to do this that I am missing?

+2


source to share


4 answers


It seems unusual that you will have many fields that are truly nullable, but if you need to describe "no value" separately for any magic domain value (for example) int

, then yes: it Nullable<T>

might help. Note that you must manually translate from null

to DbNull.Value

in the data layer, as null

on SqlParameter

means "do not send this parameter", not "send value null

" (if you see a difference).



+1


source


I think there is a confusion between field validation and nullable type here ... unless of course you have some type ... say DateTime

and want it to be null ... which would not be possible except using Nullable Type ...



If so then ... yes..Nullable types is the solution.

+1


source


Yup, sounds like a plan.

You will need to change a couple of calls though

static class NConv
{
    static T? ToNullable<T>(string str) where T : struct
    {
        return (T?)(string.IsNullOrEmpty(str) ? default(T?) : Convert.ChangeType(str, typeof(T)));
    }

    static void HowTo()
    {
        double? myBonus = NConv.ToNullable<double>(null);
    }
}

      

0


source


Build your sql dynamically based on the provided fields.

0


source







All Articles