Creating an IEnumerable Generic Class

I have a generic class that uses a type parameter

public class CustomClass<T> 

and I use it with type ObservableCollection<someClass> . All I want is to force this class to implement the IEnumerable interface, so I did the following:

 public class CustomClass<T> : IEnumerable #region Variable Declarations ... #endregion #region Constructor and CustomClass<T> properties and methods ... #endregion #region Here I add the code for IEnumerable to work private T theObservableCollection { get { if (typeof(T) == typeof(ObservableCollection<someClass>)) return theObservableCollection; else return default(T); } } //Create a public GetEnumerator method, the basic ingredient of an IEnumerable interface. public IEnumerator GetEnumerator() { IEnumerator r = (IEnumerator)new SettingEnumerator(this); return r; } //Create a nested-class class SettingEnumerator { int index; CustomClass<T> sp; public SettingEnumerator(CustomClass<T> str_obj) { index = -1; sp = str_obj; } public object Current { get { return sp.theObservableCollection[index]; } } public bool MoveNext() { if (index < sp.theObservableCollection.Length - 1) { index++; return true; } return false; } public void Reset() { index = -1; } } #endregion 

The compiler complains:

Cannot apply indexing with [] to an expression of type 'T'

I understand that something is wrong there, but I don’t know how to accomplish what I want, which finally must succeed

 public class CustomClass<T> 

a

 public class CustomClass<T> : IEnumerable 
+4
source share
2 answers

Try executing IEnumerable<T> rather than IEnumerable

+3
source

You must indicate that T can be indexed:

 public class CustomClass<T> : IEnumerable where T : IList 
+1
source

All Articles