views:

86

answers:

2

Hi

Using c#, How can I take benefit of using nullable value types when I have a variable of object type?

For example, I have a method Insert within a class which takes 4 arguments:

public int Update(Int32 serial, object deliveryDate, object quantity, object shiftTime)
{
    ....
    ....
    ....
}

As you can guess, this method inserts a new record in a table. The table (Table1), has 4 colums: Serial int, DeliveryDate DateTime null, Quantity float not null and ShiftTime smallint null

Now, my quastion is : how can I take benefit of using nullable valuetypes and also ho can I convert object to my desirable types like DateTime?

Thank you

+2  A: 

You may take a look at the System.Nullable<T> type. It has some shortcuts in C#:

public int Update(
    int serial, 
    DateTime? deliveryDate, 
    float? quantity, 
    short? shiftTime)

Which allows you to call method like this:

Update(10, null, null, null);
Darin Dimitrov
+4  A: 

Why are your parameters of type object in the first place? Why isn't it:

public int Update(int serial, DateTime? deliveryDate,
                  double? quantity, short? shiftTime)

(Note that decimal may be a better choice than double - something to think about.)

If you can possibly change your method signature, that's probably the way to go.

Otherwise, what are you really asking in your question? If you can't change the parameters, but the arguments should be of type DateTime (or null), double (or null) and short (or null) then you can just cast them to their nullable equivalents. That will unbox null to the null value of the type, and non-null values to corresponding non-null values:

object x = 10;
int? y = (int?) x; // y = non-null value 10
x = null;
y = (int?) x; // y is null value of the Nullable<int> type

EDIT: To respond to the comment...

Suppose you have a text box for the shift time. There are three options: it's filled in but inappropriately (e.g. "foo"), it's empty, or it's valid. You'd do something like this:

short? shiftTime = null;
string userInput = shiftTimeInput.Text;
if (userInput.Length > 0) // User has put *something* in
{
    short value;
    if (short.TryParse(userInput, out value))
    {
        shiftTime = value;
    }
    else
    {
        // Do whatever you need to in order to handle invalid
        // input.
    }
}
// Now shiftTime is either null if the user left it blank, or the right value
// Call the Update method passing in shiftTime.
Jon Skeet
Jon, In GUI, I have a web form which gets 4 values from user.For example, the form has a textbox for ShiftTime. but ShiftTime is not a mandatory form field. So It's possible the user doesn't enter any value for it. In this case , I should pass Null to ShiftTime column in Table1. how can I handle this one?
odiseh
@odiseh: Will edit answer to explain.
Jon Skeet
Jon, many thanks :)
odiseh