This creates a unique integer identifier for each type based on the order it accesses in thread safe mode.
For example, if you do:
int myClassId = Ident.TypeIndex<MyClass>(); int mySecondClssId = Ident.TypeIndex<MySecondClass>();
You will get 2 "TypeIndex" numbers (with mySecondClassId at least 1 more than myClassId, but potentially more, due to streaming). Later, if you call it again with the same class, it will return the same TypeIndex for that class.
For example, if I ran this using:
Console.WriteLine(Ident.TypeIndex<Program>()); Console.WriteLine(Ident.TypeIndex<Test>()); Console.WriteLine(Ident.TypeIndex<Program>()); Console.WriteLine(Ident.TypeIndex<Test>());
He will print:
0 1 0 1
However, this could be done more efficiently using Interlocked.Increment , which completely eliminates the need for locking and a synchronization object. The following gives exactly the same answer, without the need for blocking:
static class Ident { static int index = -1; static int Index { get { return Interlocked.Increment(ref index); } } private static class Type<T> { public static int id = Index; } public static int TypeIndex<T>() { return Type<T>.id; } }
source share