Initialization of instance fields vs. local variables

前端 未结 7 548
余生分开走
余生分开走 2020-11-27 06:07

I have always been wondering about why in the following example it is OK to not initialize the instance field (relying that it will have its default value)

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 06:41

    For local variables, the compiler has a good idea of the flow - it can see a "read" of the variable and a "write" of the variable, and prove (in most cases) that the first write will happen before the first read.

    This isn't the case with instance variables. Consider a simple property - how do you know if someone will set it before they get it? That makes it basically infeasible to enforce sensible rules - so either you'd have to ensure that all fields were set in the constructor, or allow them to have default values. The C# team chose the latter strategy.

提交回复
热议问题