473,387 Members | 1,515 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Compiler error with foreach?

Interesting little problem; go easy on me because I'm just a humble
scripter turned c# developer.

I've a class UserList which I auto-generated with a python script, it
extends CollectionBase and has the usual methods: this[int index],
Add, Insert, Remove and Contains. There are no differences between
this class and the other generated classes I'm using other than the
type of the contained object. The other classes can be foreach'ed
quite happily.

I knocked up a quick console app to test an aspect of this system. I
can iterate the members of the list with an integer index, but not
with a foreach. The method called inside the loop, GetName, does not
alter the underlying object, it just returns a formatted string. Can
anybody shed any light on this peculiar quirk?

// this works

UserList l = dataprovider.GetLocalUsers();

int c = l.Count;

while(c-- > 0){
User u = l[c];
Console.WriteLine(u.GetName(User.NameFormat.Initia lSurname));
}
// this causes a compiler error

// foreach(User u in l)
// {
// Console.WriteLine(u.GetName(u.NameFormat.InitialSu rname));
// }
Nov 16 '05 #1
11 1274
Flinchvoid wrote:
Interesting little problem; go easy on me because I'm just a humble
scripter turned c# developer.

<snip>

Does your user list collection class implement IEnumerable ?

--
Lasse Vågsæther Karlsen
http://www.vkarlsen.no/
mailto:la***@vkarlsen.no
PGP KeyID: 0x0270466B
Nov 16 '05 #2
extending CollectionBase isn't enough - you need to implement
GetEnumerator - see MSDN on foreach

Flinchvoid wrote:
Interesting little problem; go easy on me because I'm just a humble
scripter turned c# developer.

I've a class UserList which I auto-generated with a python script, it
extends CollectionBase and has the usual methods: this[int index],
Add, Insert, Remove and Contains. There are no differences between
this class and the other generated classes I'm using other than the
type of the contained object. The other classes can be foreach'ed
quite happily.

I knocked up a quick console app to test an aspect of this system. I
can iterate the members of the list with an integer index, but not
with a foreach. The method called inside the loop, GetName, does not
alter the underlying object, it just returns a formatted string. Can
anybody shed any light on this peculiar quirk?

// this works

UserList l = dataprovider.GetLocalUsers();

int c = l.Count;

while(c-- > 0){
User u = l[c];
Console.WriteLine(u.GetName(User.NameFormat.Initia lSurname));
}
// this causes a compiler error

// foreach(User u in l)
// {
// Console.WriteLine(u.GetName(u.NameFormat.InitialSu rname));
// }

Nov 16 '05 #3
Flinchvoid wrote:
I've a class UserList which I auto-generated with a python script, it
extends CollectionBase and has the usual methods: this[int index],
Add, Insert, Remove and Contains. There are no differences between
this class and the other generated classes I'm using other than the
type of the contained object. The other classes can be foreach'ed
quite happily.

You must implement the IEnumerable interface to enable foreach to
enumerate the collection.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 16 '05 #4
Okay, there seems to be a concensus here, but I have *other* classes
built in exactly the same way which do use foreach without any
problems.

None of the other collection classes I'm using are any different.
Another test I've run (and just re-run to make sure I'm not
hallucinating) contains the following snippet

EnquirySummaryList l = dp.SearchEnquiryDetails();

foreach(EnquirySummary e in l)
{
Console.WriteLine(e.EnquiryName);
}
EnquirySummaryList is /exactly/ the same as UserList other than the
contained type, and yet it enumerates with foreach. What am I missing?

Nov 16 '05 #5
Having scurried off to MSDN
[http://msdn.microsoft.com/library/de...lasstopic.asp]
, I find that CollectionBase implements IEnumerable. So that's not the
problem. Compiler bug, or the sinister machinations of a dark force
bent on driving me insane?

Nov 16 '05 #6
What is the compiler error you get?

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Interesting little problem; go easy on me because I'm just a humble
scripter turned c# developer.

I've a class UserList which I auto-generated with a python script, it
extends CollectionBase and has the usual methods: this[int index],
Add, Insert, Remove and Contains. There are no differences between
this class and the other generated classes I'm using other than the
type of the contained object. The other classes can be foreach'ed
quite happily.

I knocked up a quick console app to test an aspect of this system. I
can iterate the members of the list with an integer index, but not
with a foreach. The method called inside the loop, GetName, does not
alter the underlying object, it just returns a formatted string. Can
anybody shed any light on this peculiar quirk?

// this works

UserList l = dataprovider.GetLocalUsers();

int c = l.Count;

while(c-- > 0){
User u = l[c];
Console.WriteLine(u.GetName(User.NameFormat.Initia lSurname));
}
// this causes a compiler error

// foreach(User u in l)
// {
// Console.WriteLine(u.GetName(u.NameFormat.InitialSu rname));
// }

--
No virus found in this incoming message.
Checked by AVG Anti-Virus.
Version: 7.0.300 / Virus Database: 265.7.1 - Release Date: 19/01/2005

[microsoft.public.dotnet.languages.csharp]
Nov 16 '05 #7
Drat it, I've found it when trying to reproduce the bug for you: I was
trying to access the NameFormat enum in an instance of User rather than
through the class User. VS.net just borked instead of warning me.

I feel better now that logic has been restored.
Thanks to those who took two minutes to puzzle over my ineptitude.

Nov 16 '05 #8
"Anders Norås [MCAD]" <an**********@objectware.no> wrote:
Flinchvoid wrote:
I've a class UserList which I auto-generated with a python script, it
extends CollectionBase and has the usual methods: this[int index],
Add, Insert, Remove and Contains. There are no differences between
this class and the other generated classes I'm using other than the
type of the contained object. The other classes can be foreach'ed
quite happily.

You must implement the IEnumerable interface to enable foreach to
enumerate the collection.


Not necessarily. Here's an example which doesn't:

using System;
using System.Collections;

class Foo
{
ArrayList list = new ArrayList();

internal int Count
{
get
{
return list.Count;
}
}

internal string this[int i]
{
get
{
return (string)list[i];
}
}

internal void Add (string x)
{
list.Add(x);
}

public PseudoEnumerator GetEnumerator()
{
return new PseudoEnumerator(this);
}
}

class PseudoEnumerator
{
int current = -1;
Foo foo;

internal PseudoEnumerator (Foo foo)
{
this.foo = foo;
}

public bool MoveNext()
{
current++;
return current < foo.Count;
}

public string Current
{
get
{
return foo[current];
}
}
}

class Test
{
static void Main()
{
Foo f = new Foo();
f.Add ("Hello");
f.Add ("there.");
f.Add ("No");
f.Add ("IEnumerator");
f.Add ("here...");

foreach (string x in f)
{
Console.WriteLine (x);
}
}
}

See the C# language spec for more details.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
Thanks Jon, I wasn't aware of this.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 16 '05 #10
>> You must implement the IEnumerable interface to enable foreach to
enumerate the collection.


Not necessarily. Here's an example which doesn't:


Very interesting but Iam wondering why this works with foreach/IEnumerable
but not with using/IDisposable.
Nov 16 '05 #11
cody <de********@gmx.de> wrote:
You must implement the IEnumerable interface to enable foreach to
enumerate the collection.


Not necessarily. Here's an example which doesn't:


Very interesting but Iam wondering why this works with foreach/IEnumerable
but not with using/IDisposable.


Well, because the language specification says it does :)

The reason it's there is to allow people to implement a strongly-typed
enumerator - there's no equivalent need with IDisposable.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Xeon | last post by:
Hi, Is there anyway to set a custom error handler which is actually a method of a class? i.e. setting the method eh() of class foo as error handler in the snippet below. class foo { function...
13
by: | last post by:
I'm curious if anyone knows why the C# and VB.NET compilers don't automatically call Dispose() on objects that support IDisposable when they go out of scope. I asked a co-worker and his response...
15
by: Mike Lansdaal | last post by:
I came across a reference on a web site (http://www.personalmicrocosms.com/html/dotnettips.html#richtextbox_lines ) that said to speed up access to a rich text box's lines that you needed to use a...
2
by: Harold Howe | last post by:
Howdy all, I am getting a compiler error regarding a consrained conversion. It complains that it can't make the type conversion, even though the generic type argument inherits from the target of...
6
by: Patient Guy | last post by:
I am a newcomer to using PHP but not to programming (C, C++, Javascript). I am playing around with classes and wanted to make a function that has a method simply for producing either plain text...
10
by: happyse27 | last post by:
Hi All, I got this apache errors(see section A1 and A2 below) when I used a html(see section b below) to activate acctman.pl(see section c below). Section D below is part of the configuration...
11
by: xenoix | last post by:
hey there, im reasonably new to C# and im currently writing a backup application which im using as a learning resource. My PC :- Visual Studio 2005 .NET Framework 2 Component Factory Krypton...
3
by: broll911 | last post by:
I am gettin a error message on this script can someone help me. I am a complete newbie on this stuff. Thanks in advance for any help you can give me. here is the error. Parse error: syntax error,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.