Why C# local variables must be initialized?

前端 未结 8 578
春和景丽
春和景丽 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:11

    Local variables have to be assigned before they can be used. Class fields however get their default value.

    An example:

    public bool MyMethod()
    {
        bool a;
    
        Console.Write(a); // This is NOT OK.
    
        bool b = false;
    
        Console.Write(b); // This is OK.
    }
    
    class MyClass
    {
        private bool _a;
    
        public void MyMethod()
        {
            Console.Write(_a); // This is OK.
        }
    }
    

提交回复
热议问题