futurenext110
futurenext110

Reputation: 2109

Way to check for null value in if condition

I have the following line of code, which is giving me trouble of NPE

   ServeUrl = ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment);

When I write this in the following way, I no longer get the NPE

  if (ConfigurationManager.GetSection("Servers") != null && ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment) != null)
                            {
                                ServeUrl = ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment);
                            }

Somwhow, the above thing does not look good to my eyes. How can I write this in a better way?

Upvotes: 0

Views: 6515

Answers (3)

bhavya joshi
bhavya joshi

Reputation: 1136

I would have used this(FYI,i haven't tried this in compiler):

 if (ConfigurationManager.GetSection("Servers")?.Get(ment) is NameValueCollection nvc)
                        {
                            ServeUrl = nvc;
                        }

Upvotes: 0

Talha Akbar
Talha Akbar

Reputation: 10030

  1. != means not equal to and == means equal to

  2. If you can't use NULL you can use ""

Apply the condition with logic and then even after it is not getting what you want then:

  1. condition will be false and you also used AND logical operator

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499760

I'd extract a temporary variable:

var section = (NameValueCollection)ConfigurationManager.GetSection("Servers");
if (section != null && section.Get(ment) != null)
{
    ...
}

Or even:

var section = (NameValueCollection)ConfigurationManager.GetSection("Servers");
if (section != null)
{
    var url = section.Get(ment);
    if (url != null)
    {
        ServeUrl = url;
    }
}

What would you want to do if GetSection returned null though? Can you actually keep going?

Upvotes: 5

Related Questions