What is the difference between bool and Boolean ty

2020-01-23 16:41发布

What is the difference between bool and Boolean types in C#?

标签: c# types boolean
14条回答
贼婆χ
2楼-- · 2020-01-23 17:03

I realise this is many years later but I stumbled across this page from google with the same question.

There is one minor difference on the MSDN page as of now.

VS2005

Note:

If you require a Boolean variable that can also have a value of null, use bool. For more information, see Nullable Types (C# Programming Guide).

VS2010

Note:

If you require a Boolean variable that can also have a value of null, use bool?. For more information, see Nullable Types (C# Programming Guide).

查看更多
闹够了就滚
3楼-- · 2020-01-23 17:03

bool is an alias for the Boolean class. I use the alias when declaring a variable and the class name when calling a method on the class.

查看更多
混吃等死
4楼-- · 2020-01-23 17:03

bool is an alias for Boolean. What aliases do is replace one string of text with another (like search/replace-all in notepad++), just before the code is compiled. Using one over the other has no effect at run-time.

In most other languages, one would be a primitive type and the other would be an object type (value type and reference type in C# jargon). C# does not give you the option of choosing between the two. When you want to call a static method defined in the Boolean class, it auto-magically treats Boolean as a reference type. If you create a new Boolean variable, it auto-magically treats it as a reference type (unless you use the Activator.CreateInstance method).

查看更多
Luminary・发光体
5楼-- · 2020-01-23 17:05

Perhaps bool is a tad "lighter" than Boolean; Interestingly, changing this:

namespace DuckbillServerWebAPI.Models
{
    public class Expense
    {
        . . .
        public bool CanUseOnItems { get; set; }
    }
}

...to this:

namespace DuckbillServerWebAPI.Models
{
    public class Expense
    {
        . . .
        public Boolean CanUseOnItems { get; set; }
    }
}

...caused my cs file to sprout a "using System;" Changing the type back to "bool" caused the using clause's hair to turn grey.

(Visual Studio 2010, WebAPI project)

查看更多
看我几分像从前
6楼-- · 2020-01-23 17:09

I don't believe there is one.

bool is just an alias for System.Boolean

查看更多
欢心
7楼-- · 2020-01-23 17:09

They are the same. Boolean helps simplify conversion back and forth between C# and VB.Net. Most C# programmers tend to prefer 'bool', but if you are in a shop where there's a lot of both VB.Net and C# then you may prefer Boolean because it works in both places.

查看更多
登录 后发表回答