开发者

Optimising this method c#

开发者 https://www.devze.com 2023-02-17 11:55 出处:网络
I have a method which basically looks at a variable and if its bool IsSelected == true then it sets the value to false,if not sets it to true.

I have a method which basically looks at a variable and if its bool IsSelected == true then it sets the value to false, if not sets it to true.

Currently I have it written like

if( A.IsSelected)
{
A.IsSelected = false;
}
else
{
A.IsSelected = true;
}

Is it possible to write this like

A.IsSelected = !A.IsSelected 

Sorry that this is a bit of a trivial question i'开发者_开发技巧m just trying to cut down the ammount of code in my class and I Cant build the software to test it right now.

I know doing if (!A.IsSelected) will invert the bool but I wasnt sure it would work in this way for setting the value. Thanks


Yes it is possible and done all the time.


Like @Daniel A. White points out, it's perfectly possible and very often done.

However, the variable must be a plain boolean; it cannot be Nullable. If it's null, then the expression will fail.


You can also cut down the code if you use ternary operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消