30

This is my class

public class csWordSimilarity
{
    public int irColumn1 = 0;
    public int irColumn2 = 0;
    public int irColumn3 = 0;
    public int irColumn4 = 0;
    public int irColumn5 = 0;
}

I want to make that class iterable to be used like the way below

foreach (int irVal in myVarWordSimilarity)
{

} 

myVarWordSimilarity is csWordSimilarity type. So I want to iterate all public int variables. How do I need to modify csWordSimilarity class for making it iterable like the way above.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • 1
    Is there a reason why you would not use `List`? If yes, then look at implementing IEnumerable. – Davin Tryon Feb 26 '12 at 16:58
  • Reference : [How to use foreach loop with custom objects](http://stackoverflow.com/a/348977/1004522). Go through this and it will also help you understand the usage whenever you want. – Ebad Masood Feb 26 '12 at 17:03

2 Answers2

39

You can implement IEnumerable and have the GetEnumerator override return an "iterator" over the variables using the yield statement

class csWordSimilarity : IEnumerable<int>
{
    private int _var1 = 1;
    private int _var2 = 1;
    private int _var3 = 1;
    private int _var4 = 1;

    public IEnumerator<int> GetEnumerator()
    {
        yield return _var1;
        yield return _var2;
        yield return _var3;
        yield return _var4;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
Mizux
  • 8,222
  • 7
  • 32
  • 48
edvaldig
  • 2,301
  • 16
  • 17
7

Implement IEnumerable. See Using Iterators (C# Programming Guide)

In your case you could just use the built-in iterator of a List like so:

using System;
using System.Collections.Generic;

class csWordSimilarity : IEnumerable<int> {
    public int irColumn1 = 0;
    public int irColumn2 = 0;
    public int irColumn3 = 0;
    public int irColumn4 = 0;
    public int irColumn5 = 0;

    public IEnumerator<int> GetEnumerator() {
        return (new List<int>() { 
            irColumn1, irColumn2, irColumn3, irColumn4, irColumn5 
        }).GetEnumerator();
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
}
Mizux
  • 8,222
  • 7
  • 32
  • 48
Joshua Honig
  • 12,925
  • 8
  • 53
  • 75
  • 2
    There is a considerable overhead in instantiating a new List instance for the sole purpose of returning an enumerator of it, the yield statement simplifies this and is more optimal. – edvaldig Feb 26 '12 at 17:06
  • @edvaldig I think it's a matter of preference. If you're going to call this millions of times, then yes use the direct `yield`. Otherwise I prefer using BCL classes and especially `List` where convenient. – Joshua Honig Feb 26 '12 at 17:09