c# inline switch in format string

Tomas Kubes

I would like to format phrase and make endings according to number of items.

string s = string.Format("There are {0} items, bla bla {1}",
 itemsCnt, 
 () => {switch(itemsCnt)
 {
    case 0:
      return "make some...";
    case 1:
    case 2:
      return "try more";
    default:
      return "enough";
 }}
);

The syntax is not right, I believe the anonymous method should work here somehow...

Update:

I could use separate formating function. I would like to use the function in Razor and I would like to see to formating logic in one place. And furthermore I was curious how to do it :-)

brz

The code creates a Func delegate and executes it:

string s = string.Format("There are {0} items, bla bla {1}",
            itemsCnt,
            new Func<string>(() =>
            {
                switch (itemsCnt)
                {
                    case 0:
                        return "make some...";
                    case 1:
                    case 2:
                        return "try more";
                    default:
                        return "enough";
                }
            })()
            );

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related