private static int _nextItemIndex = 0;
public int Value { get; set; }
public int Index { get; private set; }
public IndexedItem(int value)
public static int GetNextIndex()
int nextIndex = Interlocked.Increment(ref _nextItemIndex) -1;
if (nextIndex == int.MaxValue - 1)
throw new InvalidOperationException("Cannot create more IndexedItem objects. Index is approaching Int32.MaxValue.");
public static void Main(string[] args)
IndexedItem item1 = new IndexedItem(10);
Console.WriteLine($"Item 1: Value = {item1.Value}, Index = {item1.Index}");
IndexedItem item2 = new IndexedItem(25);
Console.WriteLine($"Item 2: Value = {item2.Value}, Index = {item2.Index}");
Thread thread1 = new Thread(() =>
IndexedItem item3 = new IndexedItem(5);
Console.WriteLine($"Item 3 (Thread 1): Value = {item3.Value}, Index = {item3.Index}");
Thread thread2 = new Thread(() =>
IndexedItem item4 = new IndexedItem(15);
Console.WriteLine($"Item 4 (Thread 2): Value = {item4.Value}, Index = {item4.Index}");
IndexedItem item5 = new IndexedItem(30);
Console.WriteLine($"Item 5: Value = {item5.Value}, Index = {item5.Index}");