Why C# local variables must be initialized?

前端 未结 8 572
春和景丽
春和景丽 2020-12-03 22:28

I am reading MCTS Self Paced Training Kit (70-536) Edition 2 and in the 1st chapter we have the following.

How to Declare a Value Type Variable To

相关标签:
8条回答
  • 2020-12-03 23:22

    Do make it Role of THUMB in C# and VB.net that before calling any variable, do initilize it first. like

    int myInt; // Simple Declaration and have no value in it 
    myInt= 32; // Now you can use it as there is some value in it..
    
    0 讨论(0)
  • 2020-12-03 23:23

    The book is mostly correct when it comes to VB, but it fails to mention the difference between VB and C# in this case.

    In VB all local variables are automatically initialised:

    Sub Test()
      Dim x As Integer
      MessageBox.Show(x.ToString()) 'shows "0"
    End Sub
    

    While in C# local variables are not initialised, and the compiler won't let you use them until they are:

    void Test() {
      int x;
      MessageBox.Show(x.ToString()); // gives a compiler error
    }
    

    Also, it's not clear whether the quote from the book is actually talking about local variables or class member variables. Class member variables are always initialised when the class instance is created, both in VB and C#.

    The book is wrong when it says that "Value types have an implicit constructor". That is simply not true. A value type is initialised to its default value (if it's initialised), and there is no call to a constructor when that happens.

    0 讨论(0)
提交回复
热议问题