What is the default boolean value in C#?

前端 未结 6 925
心在旅途
心在旅途 2020-12-05 09:17

A boolean (bool) can\'t be null. And:

bool foo; if(foo){} // Use of unassigned local variable \'foo\'

Why the default value is

相关标签:
6条回答
  • 2020-12-05 09:37

    Basically local variables aren't automatically initialized. Hence using them without initializing would result in an exception.

    Only the following variables are automatically initialized to their default values:

    • Static variables
    • Instance variables of class and struct instances
    • Array elements

    The default values are as follows (assigned in default constructor of a class):

    • The default value of a variable of reference type is null.
    • For integer types, the default value is 0
    • For char, the default value is `\u0000'
    • For float, the default value is 0.0f
    • For double, the default value is 0.0d
    • For decimal, the default value is 0.0m
    • For bool, the default value is false
    • For an enum type, the default value is 0
    • For a struct type, the default value is obtained by setting all value type fields to their default values

    As far as later parts of your question are conerned:

    • The reason why all variables which are not automatically initialized to default values should be initialized is a restriction imposed by compiler.
    • private bool foo = false; This is indeed redundant since this is an instance variable of a class. Hence this would be initialized to false in the default constructor. Hence no need to set this to false yourself.
    0 讨论(0)
  • 2020-12-05 09:41

    The default value is indeed false.

    However you can't use a local variable is it's not been assigned first.

    You can use the default keyword to verify:

    bool foo = default(bool);
    if (!foo) { Console.WriteLine("Default is false"); }
    
    0 讨论(0)
  • 2020-12-05 09:46

    The default value for bool is false. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.

    0 讨论(0)
  • 2020-12-05 09:47

    It can be treated as defensive programming approach from the compiler - the variables must be assigned before it can be used.

    0 讨论(0)
  • 2020-12-05 09:57

    http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

    Remember that using uninitialized variables in C# is not allowed.

    With

    bool foo = new bool();
    

    foo will have the default value.

    Boolean default is false

    0 讨论(0)
  • 2020-12-05 10:01

    Try this (using default keyword)

     bool foo = default(bool); if (foo) { } 
    
    0 讨论(0)
提交回复
热议问题