Looked at from a "different" point of view, I see this as asking the question: "how can I have a .NET object that will behave like this: it will have a counter that is sequential, and is unique for all instances of the object; it will embody a DateTime, and it will 'do the right thing' to produce a formatted string result of a certain type."
One way you can approach this is create a Class:
using System;
namespace YourNameSpace
{
public class DateWithCounter
{
public int ID { set; get; }
public DateTime Date { set; get; }
public DateWithCounter(DateTime theDate)
{
Date = theDate;
ID = counter++;
}
public override string ToString()
{
return string.Format("{0}{1}{2}{3}{4}",
Date.Year,
dash,
Date.Month.ToString().PadLeft(4,zero),
dash,
ID.ToString().PadLeft(4,zero));
}
private static char dash = '-';
private static char zero = '0';
private static int counter = 0;
}
}
Okay, let's test the class:
private void SomeButton_Click(object sender, EventArgs e)
{
List<DateWithCounter> dtCounters = new List<DateWithCounter>();
DateTime adate;
for (int i = 1; i < 13; i++)
{
adate = new DateTime(2015,i, i*2);
dtCounters.Add(new DateWithCounter(adate));
Console.WriteLine(dc);
}
}
Here's the output:
2015-0001-0000
2015-0002-0001
2015-0003-0002
2015-0004-0003
2015-0005-0004
2015-0006-0005
2015-0007-0006
2015-0008-0007
2015-0009-0008
2015-0010-0009
2015-0011-0010
2015-0012-0011
I would hope that your take-away from this example is that C#/.NET offers you powerful tools to "design Objects/Types," as well as solve problems by clever coding.
I would also argue that developing the skill to design Types/Objects results in code that has a higher quality of "encapsulation."
However, I should disclaimer the above statement by saying that knowing when to take a particular coding problem and create a small utility/tool to use in that problem, and in other similar problems, is an equally valuable skill.
In this particular case, I don't see a need to create a tool/utility. Of course, it would be easy to create a generic class that had a static counter variable !
Quote:
Tell me and I forget. Teach me and I remember. Involve me and I learn.
Benjamin Franklin