In a simplest case, you could have a static field (
uint
would do fine) of some class which would initialized with 1 and be accessible from a property the way each request would increment the value:
internal uint Id {
get { return id++; }
}
private static id = 1;
Beware: this code is not thread safe. If you need to access
Id
from different threads, make sure you do it with
lock
:
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx[
^].
Now, working with static needs extra care and better be avoided. This field may not be static if the declared class has only one instance per run time, guaranteed. If does not have to be a
singleton, and it better should not, if you use this
Id
only in one place, but the
singleton pattern is the most typical universal approach to that. Please see:
http://en.wikipedia.org/wiki/Singleton_pattern[
^].
See also:
http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial[
^].
I saw many bad singleton implementations. This is a good one, for C#:
http://csharpindepth.com/Articles/General/Singleton.aspx[
^].
—SA