开发者

why in c# we need to initialize primitive type variable? [duplicate]

This question already has answers here: Initialization of instance fields vs. local variables 开发者_开发技巧 (7 answers) Closed 6 years ago.

why in c# we need to initialize primitive type variable --

static void Main(string[] args)
{
   int a;
   Console.WriteLine(a);
}

throws compile time error ...


In order to prevent potential coding mistakes, C# will not allow you to use any local variable until the compiler can prove that it has been initialized.


Purely because it is a good practice. CLR initialize them to defaults anyway - for ValueTypes.


its because of inference feature.... c # does type cast variable static unlike dynamic in python pearl so by checking type of values by which your variable is initialized type of variable is decided and verified. its done at compile time


There's another conceptual reason.

Everything in .NET is an object.

Variables are holders, which can hold references to objects or they can point to values.

Why C# should be able to let you output to Console (as in your example) a variable which holds nothing?

For me the question is, don't you find useful C# compiler preventing you from creating useless code? Any help is always useful in terms of avoiding human mistakes or wrong logic.

Maybe I should believe you say that because...

int a;

if(false) { a = 1; }

Console.WriteLine(a);

...won't compile too.

Well, why C# compiler should allow you to work with a reference to nothing? Any argument would be weak since what good program should write to console nothing? If your program doesn't need to print, just don't print.

For example, if you want to do it right, it should be:

int a;

if(false) { a = 1; } else { a = 0; }

Console.WriteLine(a);

"I want my program to show 1 if it's false, or 0 if it's true". But "show 1 if it's false, or show 'I don't know what'" is a weak argument.

It's like saying "do you want apples or emptiness?".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜