What does the bool? return type mean?

后端 未结 3 774
猫巷女王i
猫巷女王i 2020-12-06 11:44

I saw a method return bool?, does anyone know the meaning of it?

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 12:03

    Any (no-nonsense1) value type suffixed with ? makes it a nullable type:

    • int? is a nullable integer
    • bool? is nullable boolean which makes is actually a triple state boolean (true, false and null) - think of it when you need to implement some triple state behaviour.
    • ...

    In other words object type doesn't support nullable definition as object? because it's reference type and can have a value of null already.

    Real-life usage

    Nullable types are most often used against database, because they make it really easy to transform nullable int/bit/datetime/etc. columns to CLR types. Like in this example:

    create table Test
    (
        Id int identity not null primary key,
        Days int null,
        ExactDate datetime null,
        Selected bit null
    )
    

    This can easily be translated to POCO:

    public class Test
    {
        public int Id { get; set; }
        public int? Days { get; set; }
        public DateTime? ExactDate { get; set; }
        public bool? Selected { get; set; }
    }
    

    1 no-nonsense refers to all value types except Nullable which is a value type per se, but it wouldn't make any sense in making it nullable once more... Avoid such stupidity... It won't compile anyway because Nullable> i = null; can be interpreted in two ways:

    i.HasValue == false
    i.HasValue == true && i.Value.HasValue == false

提交回复
热议问题