Senthil wrote:
I am learning C#
I see you are using C# 2.0.
and now am stuck with a simple prorgam.Tried googling
but didn't get an answer :(. The following program gives me three
compilation errors.Can anyone enlighten me? Thanks.
I'll go through the errors first, before I deal with the code.
Error 1 'Collections.Tokens.TokenEnumerator' does not implement
interface member 'System.IDisposable.Dispose()'
This refers to the fact that IEnumerator<Tdescends from IDisposable,
so to implement IEnumerator<T>, you also need to implement IDisposable.
Error 2 'Collections.Tokens.TokenEnumerator' does not implement
interface member 'System.Collections.IEnumerator.Current'.
'Collections.Tokens.TokenEnumerator.Current' is either static, not
public, or has the wrong return type
This refers to the fact that IEnumerator<Talso descends from
IEnumerator, and the IEnumerator.Current property is of type 'object',
not 'string'. You'd need an explicit implementation, like this:
object IEnumerator.Current
{
get { return Current; } // uses the Current of type 'string'
}
Error 3 'Collections.Tokens' does not implement interface member
'System.Collections.IEnumerable.GetEnumerator()'.
'Collections.Tokens.GetEnumerator()' is either static, not public, or
has the wrong return type.
This is similar to the error for Current. Again, you need an explicit
implementation:
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
Note that calling methods like this, inside the type, never resolves to
an explicit interface method implementation. So, this won't recurse
indefinitely.
using System;
using System.Collections.Generic;
using System.Text;
[...]
~Tokens()
{
}
This is a finalizer. It is *highly* unlikely that your type needs a
finalizer, and its presence will make your class a lot less efficient
than it can be.
Finally, I'd like to point you to iterators, a feature of C# 2.0 which
make implementing enumerators a lot easier (ignoring the fact that you
could just return 'elements.GetEnumerator()'). Your program could be
written with iterators in the following manner:
---8<---
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Collections
{
public class Tokens : IEnumerable<String>
{
private String[] elements;
Tokens(String source, char[] delimiters)
{
elements = source.Split(delimiters);
}
~Tokens()
{
}
public IEnumerator<StringGetEnumerator()
{
for (int i = 0; i < elements.Length; ++i)
yield return elements[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public static void Main()
{
Tokens f = new Tokens("This is my first C# program", new
char[] { ' ', '#' });
foreach (String s in f)
{
Console.WriteLine(s);
}
}
}
}
--->8---
-- Barry
--
http://barrkel.blogspot.com/