10 Replies - 2562 Views - Last Post: 10 December 2010 - 02:38 PM Rate Topic: -----

#1 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

C# foreach

Posted 10 December 2010 - 09:47 AM

Why does the foreach loop though once when the collection is empty?

I am having to do this:
                foreach (ItemClass item in items)
                {
                    if (item == null) { logger.Debug("No item found"); continue; }
                    //do something with item
                }


This is really irritating as I didn't know this and now I find myself with strange errors.

Perhaps there is a better way to loop though all of the members of a collection in C#?

Is This A Good Question/Topic? 0
  • +

Replies To: C# foreach

#2 elbielefeld   User is offline

  • D.I.C Head

Reputation: 70
  • View blog
  • Posts: 217
  • Joined: 18-May 10

Re: C# foreach

Posted 10 December 2010 - 10:03 AM

Probably you are adding the null-item anywhere in your code
Was This Post Helpful? 0
  • +
  • -

#3 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C# foreach

Posted 10 December 2010 - 10:10 AM

Perhaps... but logger.debug(items.count) shows the collection to be empty. i.e. there are no items in the collection. So if you add a null to the collection the count will remain zero but the foreach will loop though any nulls?

I am having some error where nulls are popping up where they should not. My assumption was that it was caused by my misunderstanding foreach. Maybe there is another cause.

<edit>

So when I change the code to:

if (items.count > 0) {
    foreach (ItemClass item in items)
    {
        //if (item == null) { logger.Debug("No item found"); continue; } // no need to check for a null anymore
        //do something with item
    }
}


I get the effect I am looking for. i.e. NOT looping though the collection if it is empty, which is what I expected foreach to do. Apparently if the collection is empty it does one loop that that is bad.
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades   User is offline

  • Saucy!
  • member icon

Reputation: 6260
  • View blog
  • Posts: 24,030
  • Joined: 23-August 08

Re: C# foreach

Posted 10 December 2010 - 10:13 AM

What kind of collection is items?
Was This Post Helpful? 0
  • +
  • -

#5 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C# foreach

Posted 10 December 2010 - 10:16 AM

It is a List<ItemClass> behind a ICollection<ItemClass> -- that is, items is just an ICollection<ItemClass>, but it gets assigned the from a List<ItemClass>.
Was This Post Helpful? 0
  • +
  • -

#6 elbielefeld   User is offline

  • D.I.C Head

Reputation: 70
  • View blog
  • Posts: 217
  • Joined: 18-May 10

Re: C# foreach

Posted 10 December 2010 - 10:20 AM

I cannot reconstruct it. Maybe you can give some example code or change this abstract piece?

            ICollection<string> s = new List<string>();

            MessageBox.Show(s.Count.ToString());
            foreach (string s2 in s)
            {
                MessageBox.Show(s2);
            }


Was This Post Helpful? 0
  • +
  • -

#7 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C# foreach

Posted 10 December 2010 - 11:41 AM

:/ very odd... all of my test also show the foreach to work as expected rather than looping once with a null item.

The list of items is the result of webservices call so maybe it has something to do with that... debugger time!
Was This Post Helpful? 0
  • +
  • -

#8 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: C# foreach

Posted 10 December 2010 - 11:55 AM

Sorry, can't replicate it.

ICollection<object> c = new List<object>();

Debug.WriteLine("Test1: " + c.Count);
foreach(object obj in c) { Debug.WriteLine("Hit"); }

c.Add(null);
Debug.WriteLine("Test2: " + c.Count);
foreach(object obj in c) { Debug.WriteLine("Hit"); }



Results:
Test1: 0
Test2: 1
Hit



It can clearly hold null items, in which case they are counted.

e.g.
Debug.WriteLine("There are " + c.Count(delegate(object obj) { return obj == null; }) + " NULL objects.");


Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6538
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: C# foreach

Posted 10 December 2010 - 12:55 PM

If it runs one time then you have one object. That's just reality.
Put a breakpoint in the loop. Walk through with the F10 key.
When the loop proceeds for the first time the object "item" will be set to the one object in your array. You can look at it's values then to determine why it really is something and not nothing.

foreach (ItemClass item in items)
{
    if (item == null) { logger.Debug("No item found"); continue; }
    //do something with item
}


Was This Post Helpful? 0
  • +
  • -

#10 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: C# foreach

Posted 10 December 2010 - 02:11 PM

Well it is academic at this point as I have moved on. I changed the way I did things altogether.

Thank you all for your help though. I can only guess that a null was getting into the list somehow and well I have no explanation for the count == 0 other than, "I must have been mistaken" as every test I have done on the foreach seems to work as one would expect.

I am uncomfortable in C# and have been getting easily frustrated today as things are always just a little tweaked from how I would expect them to be. I was shocked to find that System.Threading does not have something like an IRunnable and that threads are just functions? kind of tweaked from a Java point of view where I would have a single object in charge of a given thread... I suppose I will more or less just do things as I have always done just have a standard function for all of my "thread control" objects...

the little differences are all very frustrating because I am trying to move pretty quickly but keep tripping.
Was This Post Helpful? 0
  • +
  • -

#11 elbielefeld   User is offline

  • D.I.C Head

Reputation: 70
  • View blog
  • Posts: 217
  • Joined: 18-May 10

Re: C# foreach

Posted 10 December 2010 - 02:38 PM

You can easily add your own IRunnable interface if you want:

namespace test
{
    public interface IRunnable
    {
        void Run();
    }

    public class myClass: IRunnable
    {
        public void Run()
        {
            Debug.Print("running");
        }
    }
}



        private void button1_Click(object sender, EventArgs e)
        {
            IRunnable myClassInstance = new myClass();

            Thread t = new Thread(myClassInstance.Run);

            t.Start();
        }



And I don't see why threads are not calling functions/methods in java. Or didn't you see the .Net Thread-Class?
You could also make your own thread class to make it look more like java:

(I'm not familar with java, this is what google showed me)

public class DemoX{
   public static void main(String[] args){
      Runnable rs = new X();
      Thread s = new Thread(rs,"Thread Nr. 1");
      s.start();
   }
}




C#...
using System.Threading;

namespace test
{
    public class myThread
    {
        Thread t;

        public myThread(IRunnable item, string name)
        {
            t = new Thread(item.Run);
            t.Name = name;
        }

        public void Start()
        {
            if (t != null) t.Start();
        }
    }
}



        private void button1_Click(object sender, EventArgs e)
        {
            IRunnable myClassInstance = new myClass();

            myThread t = new myThread(myClassInstance, "testthread");

            t.Start();
        }


This post has been edited by elbielefeld: 10 December 2010 - 02:39 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1