0

I am currently using this technique:

...
    string s = user.Gender ? "Mr." : "Mrs.";
    string body = $@"Dear {s} {user.First_name}..."
...

I want to do something like:

...
    string body = $"Dear {return user.Gender ? "Mr." : "Mrs."} {user.First_name}..."
...
1
  • 3
    Use parenthesis for the expression: $"Dear {(user.Gender ? "Mr." : "Mrs.")}" Commented Aug 1, 2020 at 12:26

2 Answers 2

4

You need to put parenthesis around the expression like so:

string body = $"Dear {(user.Gender ? "Mr." : "Mrs.")} {user.First_name}...";

The reason for that is the colon which signals a format string for something.

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

Comments

1

You can easily do so with a pair of paranteces around your conditional expression, but a better solution would be to make the greeting reusable by defining a property on the class:

public class User {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool Gender { get; set; }
    public string Title { get => Gender ? "Mr." : "Mrs."; }
    public string Greeting { get => $"{Title} {FirstName} {LastName}"; }
}

void run()
{
    var user = new User { Gender = true, FirstName = "John", LastName = "Smith" };
    string simpleSolution = $"Dear {(user.Gender ? "Mr." : "Mrs.")} {user.FirstName} {user.LastName}, hello and welcome.";
    string betterSolution = $"Dear {user.Greeting}, hello and welcome.";
}

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.