3

I got a method which receives a message and a Priority enum and returns a formatted string.

private string FormatMessage(string message, Priority priority)
{
    return string.Format("*{0,-6}* - {1}", priority, message);
}

Priority has three possible values: High, Medium and Low.

I'm using string.Format's alignment option so that the output would look nice. What I'd like the output to look like is this:

*Low*    - First message
*Medium* - Second message
*Low*    - Third message

However, what I'm getting is this:

*Low   * - First message
*Medium* - Second message
*Low   * - Third message

I understand why this is happening, but what I'd like to know is whether there's an easy (and correct) way to get the wanted output by using string.Format and without introducing any new variables.

1
  • Why not just concatenate the stars around the priority value... "*" + priority + "*" Commented Mar 15, 2012 at 8:41

2 Answers 2

9
string.Format("{0,-8} - {1}", "*" + priority + "*", message);

Or, if you're feeling fancy:

string.Format("{0,-8} - {1}", string.Format("*{0}*", priority), message);
string.Format("{0,-8} - {1}", string.Join(priority, new [] {"*", "*"}), message);
Sign up to request clarification or add additional context in comments.

4 Comments

don't forget to make the -6 into -8 :)
I was hoping there was a way to do this by modifying the first parameter only somehow, as adding *'s to the second parameter makes it a bit confusing to understand what's going to be the eventual output.
Lester, unless you override ToString() on your Priority class/struct that's not possible, I fear. If it's an enum, then even less so (unless you create a wrapping class with implicit conversion operators and a custom ToString()). Format strings are hardly Turing-complete or intended as general-purpose template engines.
Also, if you're too concerned that the string concatenation in the second argument masks the intent too much, then I'd say introducing a new variable is really the easiest way of making intent and behaviour clear.
1

Could you enlarge the first column to 8 spaces?, if so ...

private string FormatMessage(string message, Priority priority) 
{ 
    return string.Format("{0,-8} - {1}", "*" + priority.ToString() + "*", message); 
} 

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.