Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm facing the problem that C# in my case can't cast the number 1 to bool. In my scenario (bool)intValue doesn't work. I get an InvalidCastException. I know I can use Convert.ToBoolean(...) but I'm just wondering it doesn't work. Any explanation for this?

My code is

if (actualValueType.Name == "Boolean" || setValueType.Name == "Boolean")
{
   if ((bool)actualValue != (bool)setValue)
   ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

There's no need to cast:

bool result = intValue == 1;

From the docs:

The inclusion of bool makes it easier to write self-documenting code

a bool value is either true or false

1.2.1 Predefined Types (C#)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...