Pass nullable argument to a method

12,763

Solution 1

you use the right approach.

there are three options:

1) check loadEntityId.HasValue and then work with loadEntityId.Value (what you use now)

2) use loadEntityId.GetValueOrDefault()

if ((byte)cboStatus.SelectedValue == 10
    && IsUsedInProduction(loadEntityId.GetValueOrDefault()))

3) use ?? operator

if ((byte)cboStatus.SelectedValue == 10
    && (IsUsedInProduction(loadEntityId ?? 0))

Solution 2

When you declare:

private bool IsUsedInProduction(long? loadEntityId)

is actually the same as:

private bool IsUsedInProduction(Nullable<long> loadEntityId)

So when you pass null to the method, an Nullable type object is created, where loadEntityId.HasValue is equal to false and loadEntityId.Value throws and Exception when called, because the is no value. Bellow there is an example of reasonable use of Nullable. Additional Info: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

Definition example:

private bool IsUsedInProduction(long? loadEntityId)
{
     if(loadEntityId.HasValue)
     {
        //do something WITH loadEntityId.Value
     } else
     {
        //do something
     }
}

Calling examples:

IsUsedInProduction(null);
IsUsedInProduction(21);
IsUsedInProduction(23);
Share:
12,763
Leron
Author by

Leron

Updated on June 05, 2022

Comments

  • Leron
    Leron about 2 years

    This my current method but from time to time I have to deal with this problem and I want to know if there is more elegant way.

    I have : long? LoadEntityId field. I have a method where I use this as an argument :

    private bool IsUsedInProduction(long? loadEntityId)
    

    The problem is that when LoadEntityId is actually null I get Nullable object must have a value.

    What I do now is this :

    if ((byte)cboStatus.SelectedValue == 10
        && LoadEntityId.HasValue 
        && IsUsedInProduction(LoadEntityId.Value))
    

    But I think there should be better way to manage this problem.

    P.S

    It seems I wasn't clear enough in my explanation so the problem is that if I:

    if ((byte)cboStatus.SelectedValue == 10
            && IsUsedInProduction(LoadEntityId.Value))
    

    (remove LoadEntityId.HasValue check) when LoadEntityId is actually null I get exception, if I leave it - well I just look for a way to make my code work without this check.