demoncodemonkey demoncodemonkey -4 years ago 125
C# Question

One liner for throwing exception if string is null

I have some web.config settings that I want to ensure are always present. I want a neat way of doing this, such as creating a field for each setting, and in the field initializer I would somehow throw an exception if the value is null.

My original thought was to use ternary operator

?:
but that would involve writing the same key twice. I don't want to repeat the key name because this makes the code more brittle (should I ever want to rename a key I'd need to do it in 2 places). Is there any way that this duplication could be avoided?

public class MyClass
{
//what I don't really want (won't compile):
private readonly string _name1 = ConfigurationManager.AppSettings["MyName"] != null
? ConfigurationManager.AppSettings["MyName"]
: throw new Exception();

//what I sort of want (won't compile):
private readonly string _name2 = ConfigurationManager.AppSettings["MyName"]
?? throw new Exception();

...
}

Answer Source

This might be a little odd, but just to think outside the box you could add some method to your class (or as a static method) like:

public string ThrowConfigException(string message)
{
    throw new System.Configuration.ConfigurationErrorsException(message);
}

Then, you could add properties to your class that look like this:

private string _name1;
public string Name1
{
    get
    {
        return _name1 ?? (_name1 = ConfigurationManager.AppSettings["Name1"]) ?? ThrowConfigException("Name1 does not exist in the config file");
    }
}

Update in C# 7.0: You are able to throw an exception inline. The above example could now be written as:

private string _name1;
public string Name1
{
    get
    {
        return 
            _name1 ?? 
            (_name1 = ConfigurationManager.AppSettings["Name1"]) ?? 
            throw new System.Configuration.ConfigurationErrorsException(nameof(Name1) + " does not exist in the config file");
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download