private void UseFactory(IMetricFactory factory) { for (int i = 0; i < factory.Count; i++) { // this copy is important as the lambda function below // would capture i, which equals factory.Count at the end of the loop. // Therefore the lambda would always try to create factory item #factory.Count // which does not exist. // Don't remove the index variable. int index = i; var info = factory.GetMetricInfo(index); var metricInfo = new MetricInfo( info.Name, info.Category, info.UniqueName, factory.Id, g => factory.CreateInstance(index, g), (g, x) => factory.CreateInstance(index, g, x) ); _metrics.Add(metricInfo); MetricAdded?.Invoke(this, new MetricAddedEventArgs(metricInfo)); } }