1

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

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
  • 3
    Seems to be an unnecessarily complicated way of doing it. Why not compute the "ending" as you call it with a switch statement before your assignment/formatting statement? – RenniePet Aug 31 '14 at 11:33
  • string.Format doesn't have an overload that takes and executes Func objects. It just calls the ToString() method of objects in the params array, which usually doesn't make much sense for Func objects. – chris Aug 31 '14 at 11:40

2 Answers2

6

Why use a anonymous method here?

A regular would do just as fine:

private string Translate(int itemsCnt)
{
 switch(itemsCnt)
 {
    case 0:
      return "make some...";
    case 1:
    case 2:
      return "try more";
    default:
      return "enough";
 }
}

then the result is:

string s = string.Format("There are {0} items, bla bla {1}",
                         itemsCnt, 
                         Translate(itemsCnt));

The string.Format(...) has no overload that take a function

Jens Kloster
  • 11,099
  • 5
  • 40
  • 54
4

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";
                }
            })()
            );
brz
  • 5,926
  • 1
  • 18
  • 18
  • That's it. I like this solution more than separate function, because it is easy to use it in Razor and the formatting logic is in one place. – Tomas Kubes Aug 31 '14 at 11:42
  • 2
    @qub1n you want as little code as possible in your views. The method approach sounds more sensible in that case, where you'd stick the method in the viewmodel. – CodeCaster Aug 31 '14 at 11:50