Support Forums

Full Version: Cool Example - Enumerating IEnumerable of Nullable Types
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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);
Good idea ! Thanks for sharing Smile
(08-04-2012, 03:38 PM)HF~Legend Wrote: [ -> ]Good idea ! Thanks for sharing Smile

It wasn't an idea snippet per say as much as it was a demonstration to show what the return value was when the Enumerator reaches the end of it's collection.
Great demonstration!

i hope to see more, keep up the good work!
(08-05-2012, 06:31 PM)Cubs Wrote: [ -> ]Great demonstration!

i hope to see more, keep up the good work!

Thanks Smile I post lots of code on MSDN so I also enjoy sharing my examples with others. You'll see my username around the MSDN forums in the VB.net and C# sections quite a bit.