"Bit Byte" <ro**@your.box.comwrote in message
news:Qf******************************@bt.com...
(continuing with top posting - to maintain readability)
My fault on that, I'm really trying to break that old habit, still
occasionally forget :)
If I understand correctly, what you are saying is that I can use the
'foreach' statement when using my generic collection - WITHOUT having to
explicity implement it (by means of an inner class as I did earlier) -
because CollectionBase already provides this?
Correct, CollectionBase already implements a default Enumerator(). Only
reason you would need to provide your own is if you know it is doing
something wrong. And if you DO need to provide your own... I would really
recommend not using CollectionBase (see Jon's discussion about hiding
members using 'new'). That can lead to bad unintended consequences.
So I can write something like this (I know I could easily test this
myself - but I am in the middle of porting accross a huge C++ library ..)
:
void FooBar()
{
MyClass<stringcol = new MyClass<String>() ;
col.Add("hello") ;
col.Add("there") ;
col.Add("again") ;
foreach (string s in col)
Console.Write("{0}\n", s) ;
}
Will the code above work (ignoring any typos etc) ?
I don't see any immediate reason it wouldn't.
I also want to express concern that you are using generics, but using the
non-generic CollectionBase. Despite you doing
MyClass<stringcol = new MyClass<String>() ;
The Add method is simply inherited from CollectionBase, correct? Thus, it
simply takes an object as a parameter, not a string. So this would be
valid, and run successfully:
col.Add(2);
But then when you get down to your foreach() loop, it would throw an
InvalidCastException (I think that's the right one... an exception of some
form anyway) because the integer 2 is not of type string.
You might consider instead inheriting from List<Tand overriding methods as
necessary for whatever custom implementation you are doing. This again,
already implements the enumerator for you, and also provides the type safety
of ensuring only items of the generic type (strings in this example) are
added to the list.
Hope that helps, let me know if you have any other questions.
--
Adam Clauss