4

if you call checkBool, it will always return "why does this not fail"

Why is this and why do you not need to initialize _bool?

public sealed class falsefalse
{
    private static bool _bool;
    public static string checkBool()
    {
        if (!_bool)
            return "why does this not fail";
        else return "";
    }
}
puser
  • 477
  • 4
  • 16
  • That's a difference between fields (class-level variables) and local variables (variable declared inside a method (accessor etc.) body) in C#. Fields are automatically initialized to the default value of the type. Local variables must be definitely assigned to (explicitly initalized) before they can be read. – Jeppe Stig Nielsen Jun 16 '14 at 14:36

2 Answers2

5

Fields of class have their default values if you don't initialize them explicitly. Default value for type bool is false. See C# specification 10.4.4 Field initialization:

The initial value of a field, whether it be a static field or an instance field, is the default value (Section 5.2) of the field's type.

Take a look at Default Values Table (C# Reference)

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 1
    Thank you, I knew about default values, but didn't know that fields of a class would automatically use default values. – puser Jun 16 '14 at 14:16
  • 1
    For fields of a `struct`, with static fields it is entirely the same. With non-static `struct` fields, you cannot initialize at the fields declaration, you must initialize in non-static constructors. There is a default struct constructor (the parameterless one) which also sets all instance fields to their default values. – Jeppe Stig Nielsen Jun 16 '14 at 14:26
1

Fields are automatically initialized to their default. default(bool) is false, so in this case - unless specified otherwise - _bool will be initialized to false.

lc.
  • 113,939
  • 20
  • 158
  • 187