Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cool Example - Enumerating IEnumerable of Nullable Types
#1
Here's a cool example I put together for somebody who asked if the Current value from the GetEnumerator.MoveNext method returned Null if it was finished Enumerating a collection. The answer to that is no, not a true Null value anyways, Null value in terms of the default for that specific type, but not true null... Unless, of course we're incorporating Nullable types into the equation, which is what I did for him as an example:

Code:
Dim i As IEnumerable(Of Nullable(Of Integer)) = "012345".Select(Function(x) New Nullable(Of Integer)(Integer.Parse(x)))

Dim strE As IEnumerator(Of Nullable(Of Integer)) = i.GetEnumerator
While (strE.MoveNext())
    Console.WriteLine(strE.Current)
End While

Dim test As Nullable(Of Integer) = strE.Current
Console.WriteLine("HasValue: " & test.HasValue)
Console.WriteLine("Actual Value: " & test)

Check this out, and see that the Current value for the Enumerator does in fact hold Null (true Null), when we finish our Enumeration past the last element in the collection of IEnumerable.

Take this example into consideration now, and see that it's not Null, but the default 'Nothing' value for Integer... 0... :

Code:
Dim i As IEnumerable(Of Integer) = "012345".Select(Function(x) Integer.Parse(x))

Dim strE As IEnumerator(Of Integer) = i.GetEnumerator
While (strE.MoveNext())
    Console.WriteLine(strE.Current)
End While

Dim test As Nullable(Of Integer) = strE.Current
Console.WriteLine("HasValue: " & test.HasValue)
Console.WriteLine("Actual Value: " & test)

C# Version:
Code:
IEnumerable<int> i = "012345".Select(x => int.Parse(x.ToString()));

IEnumerator<int> strE = i.GetEnumerator();
while (strE.MoveNext())
{
    Console.WriteLine(strE.Current);
}

Nullable<int> test = strE.Current;
Console.WriteLine("HasValue: " + test.HasValue);
Console.WriteLine("Actual Value: " + test);

Nullable types C# Version:
Code:
IEnumerable<int?> i = "012345".Select(c => new int?(int.Parse(c.ToString())));

IEnumerator<int?> strE = i.GetEnumerator();
while (strE.MoveNext())
{
    Console.WriteLine(strE.Current);
}

int? test = strE.Current;
Console.WriteLine("HasValue: " + test.HasValue);
Console.WriteLine("Actual Value: " + test);
Reply


Messages In This Thread
Cool Example - Enumerating IEnumerable of Nullable Types - by AceInfinity - 08-01-2012, 09:13 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Source] Proxy Grabber [Cool] Hell Guardian 12 9,311 04-07-2015, 11:46 AM
Last Post: polas
  Get Cool Custom Buttons [VB.NET] [Source] Vorfin 30 11,954 04-02-2011, 01:49 PM
Last Post: h4yr0
  [Cool] Clipboard - Copy/Cut Logger ! BlackSpider 8 2,391 04-18-2010, 12:16 AM
Last Post: RaZoR03

Forum Jump:


Users browsing this thread: 1 Guest(s)