views:

92

answers:

4

When i apply IEnumerator and perform MoverNext() will it traverse like C-Style 'a' 'p' 'p' 'l' 'e' '\o' until it finds null character?I thought it would return the entire string.How does the enumeration work here?

    string ar = "apple";

    IEnumerator enu = ar.GetEnumerator();

    while (enu.MoveNext())
    {

        Console.WriteLine(enu.Current);
    }

I get output as

a
p
p
l
e
+3  A: 

The null character is not an inherent part of a CLR / .Net string and hence will not show up in the enumeration. Enumerating a string will return the characters of the string in order

JaredPar
+8  A: 

Strings are not null-terminated in C#. Or, rather, the fact that strings are null-terminated is an implementation detail that is hidden from the user. The string "apple" has five characters, not six. You ask to see those five characters, we show all of them to you. There is no sixth null character.

Eric Lippert
How does C# find that the traverse comes to eng?
sorry traverse comes to end
It know the lenght of the string. No need for a terminator.
EricSchaefer
Correct. As another implementation detail, the runtime stores the length of the string as part of the data of the string. An interesting consequence of this fact is that it is thereby possible to have strings which contain "embedded null" characters, though frankly, I don't recommend it.
Eric Lippert
Is the null-termination feature of CLR strings primarily a design choice to avoid copying when passing a string to unmanaged code? Also, does this place some arbitrary upper bound on the length of a string (like int.MaxValue)?
LBushkin
I didn't design the string implementation, so I cannot say for sure what they were thinking. But yes, use of common idioms when treating strings as pinned memory buffers certainly seems like a reasonable design goal. And yes, because the Length property of a string is an int, that limits the number of chars to be the largest possible int.
Eric Lippert
+2  A: 

An enumerator returns each element of the underlying container per iteration (MoveNext() call). In this case, your container is a string and its element type is char, so the enumerator will return a character per each iteration.

Also, the length of the string is known by the string type, which may be leveraged by the enumerator implementation to know when to terminate its traversal.

Steve Guidi
+2  A: 

C# strings are stored like COM strings, a length field and a list of unicode chars. Therefore there's no need of a terminator. It uses a bit more memory (2 bytes more) but the strings themselves can hold nulls without any issues.

Another way to parse strings that uses the same functionality as your code only is more C#-like is:

string s="...";
foreach(char c in s)
  Console.WriteLine(c);
Blindy