What does the bool? return type mean?

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

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

3条回答
  •  庸人自扰
    2020-12-06 11:48

    In C#, the "primitive" types can't hold a null value:

    int blah = null;
    

    That will make an exception because 'int' can't hold a null value.

    Same with double, float, bool, DateTime...

    That is fine really. The problem comes when you are using databases. In a database you can have rows that can be null, like Age (that is an int).

    How do you hold that row on an object? Your int cannot hold the null value and the row can have null.

    For that reason MS created a new struct, the Nullable, you can pass to that struct a "primitive" type (or a struct) to make it nullable like:

    Nullable blah = null;
    

    That will not make an exception, now, that variable can hold an int and a null.

    Because Nullable is too long, MS created some kind of alias: If you put the '?' after the type, it becomes nullable:

    int? blah = null;
    Nullable blah = null;
    

    This two lines are EXACTLY the same but the first one is easier to read.

    Something like that :)

提交回复
热议问题