Span does not require local variable assignment. Is that a feature?

前端 未结 3 1781
北荒
北荒 2021-01-04 06:29

I notice that the following will compile and execute even though the local variables are not initialized. Is this a feature of Span?

void Uninitialized()
{
          


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 07:30

    More or less this is by design, since it depends heavily if the underlying struct holds any fields itself.

    This code compiles for example:

    public struct MySpan
    {
        public int Length => 1;
    }
    
    static class Program
    {
        static void Main(string[] args)
        {
            MySpan s1;
            var l1 = s1.Length;
        }
    }
    

    But this code doesn't:

    public struct MySpan
    {
        public int Length { get; }
    }
    
    static class Program
    {
        static void Main(string[] args)
        {
            MySpan s1;
            var l1 = s1.Length;
        }
    }
    

    It seems that in that case, the struct is defaulted, and that is why it doesn't complain about a missing assignment. That it doesn't detect any fields is a bug, as explained in Marc's answer.

提交回复
热议问题