Hi All,
I'm trying to write a program that when it gets a piece of data back it will add a suitable padding to it to allow for processing. I have a rough bit of code using if then, if() loops that works. In the interest of this being maintainable later I am trying to use a switch() case the if() version is below: I need it to test over a range of values as while each case falling to the next works for a few values when it gets to 100's it is not really possible. How do you do this properly I have done this in C I know I have!
//works!!!!
if ((FileTotal < 9) || (FileTotal == 9))
FileIDFiller = "000";
if ((FileTotal < 99) && (FileTotal > 9))
FileIDFiller = "00";
if ((FileTotal < 999)&&(FileTotal >99))
FileIDFiller = "0";
if (FileTotal > 999)
FileIDFiller = "";
the switch() version I have tried is below also:
switch (Value)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
MessageBox.Show("000");
break;
case 10:
case 99:
MessageBox.Show("00");
break;
case 100:
case 999:
MessageBox.Show("0");
break;
case 1000:
MessageBox.Show("");
break;
default:
MessageBox.Show("Something broke!!");
break;
}
There does not appear to be one!
Loading
VulpesPosted Jun 12, 2012, 9:17 AM
The same also applies to C and C++.
However, VB6 and VB.NET do allow you to use a range of values and it may be these languages which you were thinking about, Glenn.
Consequently, the only practical proposition when you're using C# is to code an if / else if / else ladder as you're already doing, though you can simplify it a bit to this:
Glenn PattonPosted Jun 12, 2012, 12:03 PM
VulpesPosted Jun 12, 2012, 10:31 AM
Glenn PattonPosted Jun 12, 2012, 10:06 AM
VulpesPosted Jun 12, 2012, 9:59 AM
Incidentally, you could replace your 'if' statements with this single line:
FileIDFilter = new String('0', Math.Max(4 - FileTotal.ToString().Length, 0));
It's probably a bit less performant than the 'if' statements but, what the heck, nowadays :)
Glenn PattonPosted Jun 12, 2012, 9:46 AM
VulpesPosted Jun 12, 2012, 9:43 AM
If it predates 1989, that's quite likely as C hadn't been standardized at the time even though the language went back to the early 1970's.
Glenn PattonPosted Jun 12, 2012, 9:37 AM
Glenn PattonPosted Jun 12, 2012, 8:17 AM
Glenn PattonPosted Jun 12, 2012, 8:12 AM
Nattudurai EswaramurthyPosted Jun 12, 2012, 8:04 AM
case 0-4:
//Do Something
Break;
case 5:
//Do Something
Break;
case 6-100:
//Do Something
Break;
case 101-1000:
//Do Something
Break;
case 1001-10000:
//Do Something
Break;
Nattudurai EswaramurthyPosted Jun 12, 2012, 8:02 AM