Wednesday, April 6, 2016

Implement IEnumerable<T> interface in C# and VB.NET

Hello, According to MSDN, IEnumerable<T> Interface exposes the enumerator, which supports a simple iteration over a collection of a specified type. Collections such as List<T> implements this interface. For this demo, I created a simple class that implements IEnumerable<string>. You can use concrete types instead of string or ordinary data types. Presented are two classes in different languages (C# and VB.NET) that implements the interface. Notice that in VB.NET, the yield functionality is applied in an Iterator function.

C#.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
namespace IEnumerableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MessagingApp myObject = new MessagingApp();
 
            foreach (string item in myObject)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadLine();
        }
    }
 
    public class MessagingApp : IEnumerable<string>
    {
        string[] Messages = { "Test", "C#Program", "Testing" };
 
        public IEnumerator<string> GetEnumerator()
        {
            foreach (var item in Messages)
            {
                if (item == null)
                {
                    break;
                }
 
                yield return item;
            }
        }        
 
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }       
    }
}

VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Module Module1
   
    Sub Main()
        Dim myObject As New MessagingApp
        For Each item As String In myObject
            Console.WriteLine(item)
        Next
        Console.ReadLine()
    End Sub
 
    Public Class MessagingApp
        Implements IEnumerable(Of String)
        Dim Messages As String() = {"Test", "VBProgram", "Hello"}
 
        Public Iterator Function GetEnumerator() As IEnumerator(Of String) _
        Implements IEnumerable(Of String).GetEnumerator
            For Each item As String In Messages
                If item = Nothing Then
                    Exit For
                End If
 
                Yield item
            Next
        End Function
 
        Private Function GetEnumerator1() As IEnumerator _ 
        Implements IEnumerable.GetEnumerator
            Return Me.Messages.GetEnumerator()
        End Function
 
    End Class
    
End Module

References:
Walkthrough: Implementing IEnumerable(Of T) in Visual Basic
IEnumerable Interface

0 comments:

Post a Comment