0

Simple request -- does anybody know a way to consolidate this to one line: edit - I was NOT confused about pre vs post increment operators. The question I posted should have worked, I honestly do not know what happened. somewhere between VS and SO I fixed it.

 startingMask++;
 string mask2 = startingMask.ToString().PadLeft(3, '0');

Something like

string mask2 = (startingMask++).ToString().PadLeft(3, '0');

edit -- Alright -- chill out -- :)

Here is the final full solution, I should have provided more info in my first question, I was just looking for a nudge in the right direction (the number needed and starting number will be changing via a database pull at some point):

        int startingMask = 76;
        int numberNumberNeeded = 10;
        List<string> masks = new List<string>();

        while (numberNumberNeeded > 0)
        {
        string newMask = (startingMask++).ToString().PadLeft(3, '0');
            masks.Add(newMask);
            numberNumberNeeded--;
        }
Joe Ruder
  • 2,122
  • 2
  • 23
  • 52
  • 2
    but....... why? – Jamiec May 04 '17 at 11:56
  • Jamiec posted the right question: why would you do this? It just makes your code harder to read and to understand which is a bad thing. In particular in your case it won´t even cause *any* improvement. – MakePeaceGreatAgain May 04 '17 at 12:02
  • I did a search and did not find a answer...I did not just throw it up there. – Joe Ruder May 04 '17 at 12:02
  • Sorry...I have to actually build a list with about 10 elements and was trying to avoid 20 lines of code. – Joe Ruder May 04 '17 at 12:03
  • Doing the same thing 10 times does not mean 10x{number of existing lines}. It's when you refactor your code to make it reusable, not try to squash "thing" into 1 line – Jamiec May 04 '17 at 12:03
  • "have to actually build a list with about 10 elements and was trying to avoid 20 lines of code" then you need a function that does it once and call it. DRY – rory.ap May 04 '17 at 12:04
  • I still did not want the increment on its own line. The solution is perfectly readable. Why is it such a big deal that I want to do it inline vs having to do it before? – Joe Ruder May 04 '17 at 12:13

1 Answers1

5
string mask2 = (++startingMask).ToString().PadLeft(3, '0');

Postfix ++ startingMask++ first take value and then increment value

Sufix ++ ++startingMask first increment value and then take value

BWA
  • 5,672
  • 7
  • 34
  • 45