1

How can I simplify conditional statement inside object initializer so that code will be more readible? If addNew is true, then new item is added to dictionary, otherwise it will have only one item.

...
var channel = new ChannelConf {
Name = "Abc"
Headers = !addNew ?  new Dictionary<string, string> 
          { 
               [Constants.Key1] = Id
          }
          : new Dictionary<string, string>
          {
               [Constants.Key1] = Id,
               [Constants.Key2] = Port
          }
}
...
3
  • Might want to identify the language with a tag. Commented Aug 25, 2017 at 20:49
  • you might think of using constructor overloading new ChannelConf(bool addNew) Commented Aug 25, 2017 at 22:34
  • How about not using conditionals in initalizers? if (addNew) { channel.Headers.Add(Constants.Key2, Port); } after the initialization is a vast improvement. Remember, initializers are only shorthand for after-the-fact property assignments anyway. You do not get a prize for squeezing everything in one block. Commented Aug 25, 2017 at 22:36

2 Answers 2

1

You could call a method to initialize Headers:

...
new ChannelConf {
Name = "Abc"
Headers = GetNewDictionary(addNew)
}
...

private Dictionary<string, string> GetNewDictionary(bool addNew)
{
    Dictionary<string, string> output = new Dictionary<string, string> { [Constants.Key1] = Id };

    if (addNew) { output.Add(Constants.Key2, Port); }

    return output;
}

Alternately, you could leave it the way that it is and reduce the number of lines:

...
var channel = new ChannelConf {
Name = "Abc"
Headers = !addNew ?  new Dictionary<string, string>  { [Constants.Key1] = Id }
          : new Dictionary<string, string> { [Constants.Key1] = Id, [Constants.Key2] = Port }
}
...
Sign up to request clarification or add additional context in comments.

Comments

0

I think it is a good practice to let things done through a parameterized constructor. It might be a common api consumed by others, so it is going to be easy for you to document and not have to tell how consumer should use the api.

public ChannelConf(bool addNew)
{
    Headers = !addNew
        ? new Dictionary<string, string>
        { [Constants.Key1] = Id }
        : new Dictionary<string, string>
        {
            [Constants.Key1] = Id,
            [Constants.Key2] = Port
        };
}

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.