0

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?

3 Answers 3

5

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Just one thing to add, wouldn't be GetSection() as NameValueCollection be a bit safer? Depending if getSection can return something else than NameValueCollection, which would explain the cast.
@dowhilefor: It depends on what you mean by "safer". If it's an error (e.g. in configuration or programming) for GetSection("Servers") to return some other kind of object, then I'm absolutely fine with an exception. It feels like this is the kind of situation which should stop the system coming up, rather than trying to continue.
1
  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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.