Why can't you use an unsafe keyword in an iterator context?

Considering this question, John did an excellent job with the answer ... How to read a text file using an iterator . And there was a similar question in which I answered using hocus pocus pointers. .net is there a way to read a text file from bottom to top before it got closed ....

Now I decided to try this with pointers, ok, it looks khaki and rough around the edges ...

public class ReadChar: IEnumerable <char>
{
    private Stream _strm = null;
    private string _str = string.Empty;
    public ReadChar (string s)
    {
        this._str = s;
    }
    public ReadChar (Stream strm)
    {
        this._strm = strm;
    }
    public IEnumerator <char> GetEnumerator ()
    {
        if (this._strm! = null && this._strm.CanRead && this._strm.CanSeek)
        {
            return ReverseReadStream ();
        }
        if (this._str.Length> 0)
        {
            return ReverseRead ();
        }
        return null;
    }

    private IEnumerator <char> ReverseReadStream ()
    {
        long lIndex = this._strm.Length;
        while (lIndex! = 0 && this._strm.Position! = 0)
        {
            this._strm.Seek (lIndex--, SeekOrigin.End);
            int nByte = this._strm.ReadByte ();
            yield return (char) nByte; 
        }
    }

    private IEnumerator <char> ReverseRead ()
    {
        unsafe
        {
            fixed (char * beg = this._str)
            {
                char * p = beg + this._str.Length;
                while (p--! = beg)
                {
                    yield return * p;
                }
            }
        }
    }
    IEnumerator IEnumerable.GetEnumerator ()
    {
        return GetEnumerator ();
    }
}

but found that the C # compiler could not handle this using this implementation, but was emptied when the C # compiler refused with error CS1629 - "Unsafe code may not display in iterators"

Why is this so?

+5
source share
3 answers

Eric Lippert has a great blog post on this topic: Iterator Blocks, Part Six: Why isn’t there an unsafe code?

+5
source

I want to know why you should use pointers for this at all. Why not just say:

private IEnumerator<char> ReverseRead()
{
    int len = _str.Length;
    for(int i = 0; i < len; ++i)
        yield return _str[len - i - 1];
}

?

+6

#:

26.1 Iterator... , (§27.1). , .

, , , , "". , IEnumerator .

+1

All Articles