Search code examples
c#inlineanonymous-methods

c# inline switch in format string


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 :-)


Solution

  • 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";
                    }
                })()
                );