Reputation: 69
I have a static string:
static string SERIAL = "000";
I need to increment it by 1 on a certain condition. For example, the value should be like this:
001
002
003
and so on.
I have tried different ways but haven't been able to figure it out
Upvotes: 0
Views: 1859
Reputation: 137
You could have the serial value as a integer and define a getter which will return the value as a string in the desired format. This way you can simply increment the numeric value of the serial.
As an example:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(Counter.SerialString);
Counter.Serial++;
Console.WriteLine(Counter.SerialString);
Console.ReadKey();
}
public class Counter
{
public static int Serial;
public static string SerialString
{
get
{
return Serial.ToString("000");
}
}
}
}
Upvotes: 4
Reputation: 4930
One way would be to use the PadLeft method on the ToString method.
int n = 000;
for (int i = 0; i < 100; i++)
{
n++;
Console.WriteLine(n.ToString().PadLeft(3, '0'));
}
Console.ReadLine();
Heres the method header public string PadLeft(int totalWidth, char paddingChar);
Upvotes: 1
Reputation:
If the serial is always 3 digit long, You can use an integer and when You need it as a string, just call its ToString()
method.
Upvotes: 0