Q: returning wrong type from GetEnumerator?

G

Guest

I know this is simple problem but I am so new that there is some fundamental
disconnect in my understanding of: Enumerable, Enumerator, and Generics.

As a result I am having a problem debugging this error message
"Error 1 'SimpleSite.Email.Model.Hosts' does not implement interface member
'System.Collections.IEnumerable.GetEnumerator()'.
'SimpleSite.Email.Model.Hosts.GetEnumerator()' is either static, not public,
or has the wrong return type."

....in the following simple code...:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace SimpleSite.Email.Model
{
class Hosts : IEnumerable<Dictionary<String,Host>>
{
private Dictionary<String, Host> hosts;

Hosts()
{
hosts = new Dictionary<String, Host>();
}

public void Add(Host h)
{
if (hosts.Contains(h.getId()))
{
hosts.Remove(h.getId());
}
hosts.Add(h.getId(), h);
}
public IEnumerator<Dictionary<String,Host>> GetEnumerator()
{
return (IEnumerator < Dictionary<String, Host> >)
this.hosts.GetEnumerator();
}
public Host Item(String key)
{
return hosts(key);
}
}
}

Any ideas why I am seeing this error and what I should change would be
greatly appreciated. Thanks!! - Richard
 
J

Jon Skeet [C# MVP]

rchf said:
I know this is simple problem but I am so new that there is some fundamental
disconnect in my understanding of: Enumerable, Enumerator, and Generics.

As a result I am having a problem debugging this error message
"Error 1 'SimpleSite.Email.Model.Hosts' does not implement interface member
'System.Collections.IEnumerable.GetEnumerator()'.
'SimpleSite.Email.Model.Hosts.GetEnumerator()' is either static, not public,
or has the wrong return type."

...in the following simple code...:

You're implementing System.Collections.Generic.IEnumerable<T>, but not
System.Collections.IEnumerable.

Just add:

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

and all should be well.
 
G

Guest

Thank you Jon - that did it! Seems one must specify the position in the
class hierarchy of the methods that are satisfying Interface specifications.
That was unexpected. Thanks again!
 
J

Jon Skeet [C# MVP]

rchf said:
Thank you Jon - that did it! Seems one must specify the position in the
class hierarchy of the methods that are satisfying Interface specifications.
That was unexpected. Thanks again!

No, it's not a case of specifying the position in the hierarchy. You
just need to implement one of the GetEnumerator methods explicitly
(i.e. including which interface you mean) because they both have the
same signature.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top