How to check for double if null?

Jassim Al Rahma 1,616 Reputation points
2022-03-20T20:38:02.343+00:00

Hi,

I have the following in my app:

double? latitude;
..................
..................
..................
var content = new FormUrlEncodedContent(new[]
{
     new KeyValuePair<string, string>("latitude", latitude),
}

How can I check for the vale of latitude so if it's null then pass "" otherwise pass Convert.ToString(latitude)?

Thanks,
Jassim

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-03-20T20:45:56.963+00:00

    Try...

    new KeyValuePair<string, string>("latitude", latitude.HasValue ? latitude.Value.ToString() : "")  
    

    Reference documentation.
    ?: operator (C# reference)
    Nullable value types (C# reference)

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2022-03-20T21:11:45.287+00:00

    You could do something like this:

    double? latitude = null;
    // ...
    Console.WriteLine(latitude?.ToString() ?? "");
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.