I have a generic class which uses a type parameter
public class CustomClass<T>
and I am using it with an ObservableCollection<someClass>
Type. All I want is to make this class 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 there is something wrong there, but I don't know how to accomplish what I want, which finally is to successfully make
public class CustomClass<T>
a
public class CustomClass<T> : IEnumerable