Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c# - Why must local variables have initial values?

Why must I initialize variables inside methods?

int test1; // Not initialized, but OK

public int Foo()
{
   int test2;                 // Not initialized

   int test3 = test1;         // OK
   int test4 = test2;         // An error
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Fields are automatically initialized to the logical zero for the type; this is implicit. Variables must obey "definite assignment", so must be assigned before they can be read.

ECMA 334v4

§17.4.4 Field initialization

The initial value of a field, whether it be a static field or an instance field, is the default value (§12.2) of the field’s type. It is not possible to observe the value of a field before this default initialization has occurred, and a field is thus never "uninitialized".

and

§12. Variables

... A variable shall be definitely assigned (§12.3) before its value can be obtained. ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...