Should I always/ever/never initialize object fields to default values?

前端 未结 17 2153
臣服心动
臣服心动 2020-12-09 14:49

Code styling question here.

I looked at this question which asks if the .NET CLR will really always initialize field values. (The answer is yes.) But it

17条回答
  •  猫巷女王i
    2020-12-09 15:54

    You are always safe in assuming the platform works the way the platform works. The .NET platform initializes all fields to default values. If you see a field that is not initialized by the code, it means the field is initialized by the CLR, not that it is uninitialized.

    This concern is valid for platforms which do not guarantee initialization, but not here. In .NET, is more often indicates ignorance from the developer, thinking initialization is necessary.


    Another unnecessary hangover from the past is the following:

    string foo = null;
    foo = MethodCall();
    

    I've seen that from people who should know better.

提交回复
热议问题