c# - Conditional XOR? - Stack Overflow
文章推薦指數: 80 %
There is no such thing as conditional (short-circuiting) XOR. Conditional operators are only meaningful when there's a ...
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
ConditionalXOR?
AskQuestion
Asked
11yearsago
Modified
4monthsago
Viewed
89ktimes
95
11
HowcomeC#doesn'thaveaconditionalXORoperator?
Example:
truexorfalse=true
truexortrue=false
falsexorfalse=false
c#operatorsxorboolean-operations
Share
Follow
editedAug12,2015at9:23
david.s
11.1k66goldbadges5252silverbadges8181bronzebadges
askedJun28,2011at14:12
GiladNaamanGiladNaaman
6,0881414goldbadges4949silverbadges7979bronzebadges
15
17
Howdoes!=workasasubstitute?
– PascalCuoq
Jun28,2011at14:14
47
C#doeshaveanxoroperator(x^y).Ithereforedenythepremiseofthequestion.CanyouexplainwhyyoubelievedthatC#doesnothaveanxoroperator?IaminterestedtolearnwhypeoplebelievefalsethingsaboutC#.
– EricLippert
Jun28,2011at14:15
4
@EricLippert:Ithinkhe'sreferringtologicaloperators(&|^)vsconditionaloperators(&&||).Butyou'reright(ofcourse),thereisalogicalXOR...
– BoltClock
Jun28,2011at14:15
14
@BoltClock:Oh,ifthequestionis"whyistherenoshort-circuitingxoroperator?"--howcouldtherebe?With"and"ifthefirstargumentisfalseyoudon'tneedtoevaluatethesecond.With"or",ifthefirstargumentistruethenyoudon'tneedtoevaluatethesecond.Youalwaysneedtoevaluatebothargumentsforxor,sothereisnoshortcircuitingpossible.
– EricLippert
Jun28,2011at14:18
6
ThequestionitselfisonebettersuitedtoMicrosoft-andsothat'sadecentreasontodownvote-butifwhoeverdownvoteditdidsobecauseofthe^operator,thenyouneedtoreadwithmoreattentiontodetail,becausethequestionwasconditionalvs.logical,notsimply"whyisn'tthereanXOR".
– TheEvilGreebo
Jun28,2011at14:21
|
Show10morecomments
11Answers
11
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
315
Conditionalxorshouldworklikethis:
truexorfalse=true
truexortrue=false
falsexortrue=true
falsexorfalse=false
Butthisishowthe!=operatoractuallyworkswithbooltypes:
(true!=false)//true
(true!=true)//false
(false!=true)//true
(false!=false)//false
Soasyousee,thenonexistent^^canbereplacedwithexisting!=.
Share
Follow
editedMar1at15:47
StayOnTarget
10k1010goldbadges4545silverbadges6969bronzebadges
answeredFeb2,2013at18:02
piotrpopiotrpo
12k77goldbadges4040silverbadges5858bronzebadges
7
56
Thisisactuallytheonlyanswerthataddressesthequestiondirectlyandcorrectly.
– usr
Mar22,2013at14:31
50
IamsittingherefacepalmingmyselfthatIdidn'trealize!=wouldworkforthis.
– AdamMc331
Aug19,2015at15:49
2
Theansweriscorrectbutthecommentsaren't.Itdoesnotaddressthequestion,whichis"whydoesn'tC#haveaconditionalXOR?".Strictlyspeakingthisisn'talogicaloperator,it'sarelationalequalityoperator.WhiletheresultisthesameasXOR,itisinadifferentclass.ItonlycomparestoXORwhentestingtwobooleanvalues,andbothsidesoftheoperatorstillmustbeevaluated.
– TheEvilGreebo
May17,2017at2:22
3
@TheEvilGreebo-Whatyousayistrue;the!=operatorisnottechnicallyaconditionalXORoperator.However,thisanswereffectivelysays,"AconditionalXORoperatordoesn'texistbecausethe!=operatordoes."That'showIreadit,anyway.
– Syndog
May22,2017at17:33
6
IthinkprettymucheveryoneendeduptothispostactuallywantedtowriteXORonBooleans.likethereislogicalANDandORbutnothingasXOR.oratleastwedidn'trealize!=:)@TheEvilGreebo
– M.kazemAkhgary
Dec26,2017at13:47
|
Show2morecomments
130
InC#,conditionaloperatorsonlyexecutetheirsecondaryoperandifnecessary.
SinceanXORmustbydefinitiontestbothvalues,aconditionalversionwouldbesilly.
Examples:
LogicalAND:&-testsbothsideseverytime.
LogicalOR:|-testbothsideseverytime.
ConditionalAND:&&-onlyteststhe2ndsideifthe1stsideistrue.
ConditionalOR:||-onlytestthe2ndsideifthe1stsideisfalse.
Share
Follow
editedJun28,2011at14:21
mdm
12.2k55goldbadges3333silverbadges5353bronzebadges
answeredJun28,2011at14:17
TheEvilGreeboTheEvilGreebo
6,78633goldbadges2727silverbadges5454bronzebadges
9
49
AnXORoperatorwouldnotviolatetheconvention"conditionaloperatorsonlyexecutetheirsecondaryoperandifnecessary".Itwouldjustalwaysbenecessary.
– NathanKovner
Dec18,2015at21:57
2
ConditionalXORcouldbeaniceandelegantshortcutforsomeparticularpatterns,althoughnotsureifjustifiedenoughtoincludeitinthelanguage.AnexampleofsuchpatternswhereXORmightproveuseful,isConditionalNegation:WhenaBooleanexpressionshouldbenegatedornot,givenasecondbooleanexpression.
– SalvadorGomez
May5,2016at22:21
1
Haven'trespondedtothisinsometimebuttorespondtopopularcommentby@KhyadHalda:Whywouldyoueverbuildsomethingyouknowwouldneverbeused?You'dbedeliberatelywritingdeadcode.
– TheEvilGreebo
May15,2017at18:47
2
How,ever,wouldaconditionalXOReverbeuseful?AconditionalXORcannoteverevaluatewithoutcomparingbothsidestodeterminethattheyareorarenotequal.EventhenotionofaconditionalXORcomparingtwoboolsmuststillcheckthevalueofeachboolandtesttheequality.
– TheEvilGreebo
May28,2017at22:35
1
It'sassillyasaconditionaladditionoperator.Whynotmakeanotheroperatorforconditionaladdition,where(a+b)onlyevaluatesbwhenbisnecessary?JustlikewithconditionalXOR,thiswouldn'tviolatetheconventionofconditionaloperators,it'sjustthatthesecondargumentwouldalwaysbenecessary.There'snousecaseforthisever.AndI'mnotjustbeingpedanticwiththisexample--theXORoperationisessentiallya1-bitaddition.
– KevinHolt
May15,2019at21:16
|
Show4morecomments
32
ThereisthelogicalXORoperator:^
Documentation:C#Operatorsand^Operator
Thedocumentationexplicitlystatesthat^,whenusedwithbooleanoperands,isabooleanoperator.
"forthebooloperands,the^operatorcomputesthesameresultasthe
inequalityoperator!=".
(Andasnotedinanotheranswer,that'sexactlywhatyouwant).
Youcanalsobitwise-xorintegeroperandswith^.
Share
Follow
editedMar1at15:50
StayOnTarget
10k1010goldbadges4545silverbadges6969bronzebadges
answeredJun28,2011at14:15
iceawayiceaway
1,12411goldbadge77silverbadges1212bronzebadges
4
3
Logical,notconditional.Logicaland=&,conditionaland=&&.He'saskingaboutConditional.
– TheEvilGreebo
Jun28,2011at14:16
3
Itisbinary,notlogical.Itassumesthatboolsareeither0or1whichisnottrueontheCLR.
– usr
Mar22,2013at14:29
3
sorry,thisanswerdoesnotactuallyanswerthequestionaboutCONDITIONALoperators.thisisabitopperator
– NathanTregillus
Apr14,2017at16:14
5
Fortherecord,thedocumentationlinkedinthisanswerexplicitlystatesthat^,whenusedwithbooleanoperands,isabooleanoperator."forthebooloperands,the^operatorcomputesthesameresultastheinequalityoperator!=".Youcanalsobitwise-xorintegeroperandswith^.C#isnotC.
– 15ee8f99-57ff-4f92-890c-b56153
May17,2019at13:31
Addacomment
|
25
Justasaclarification,the^operatorworkswithbothintegraltypesandbool.
SeeMSDN's^Operator(C#Reference):
Binary^operatorsarepredefinedfortheintegraltypesandbool.Forintegraltypes,^computesthebitwiseexclusive-ORofitsoperands.Forbooloperands,^computesthelogicalexclusive-orofitsoperands;thatis,theresultistrueifandonlyifexactlyoneofitsoperandsistrue.
Maybethedocumentationhaschangedsince2011whenthisquestionwasasked.
Share
Follow
editedAug31,2018at21:57
jpmc26
26.3k1111goldbadges9090silverbadges140140bronzebadges
answeredJun13,2016at11:50
RichardCLRichardCL
1,4171010silverbadges99bronzebadges
2
2
beenprogramminginc#alongtime,neverknewthis!thanks@RichardCL!
– NathanTregillus
Apr14,2017at16:19
Thisisgoodinformationbutseemsmoreappropriateasacommentoredittotheotheranswerthatmentions^andpredatesthisonebyfiveyears.Idoubtanythinghaschanged.
– Chris
Jul30,2019at19:49
Addacomment
|
13
AsaskedbyMarkL,Hereisthecorrectversion:
Func
延伸文章資訊
- 1C# Bitwise and Bit Shift Operators - Programiz
Bitwise XOR
- 2[邏輯運算] 利用互斥進行兩數互換
II. 程式. 以往的做法會宣告一個temp 變數來當互換的暫存如果利用XOR 寫法就變的非常簡單,只要三行就完成互換的動作 ( ^ 為C#語法中的XOR 運算子).
- 3位元運算子(二進制) - iT 邦幫忙
... 與運算子(+、-、*、/、>、<....等)-來用C#算數學吧!(下). C#與ASP.Net入門-我要成為工程師!! 系列第9 篇 ... XOr(互斥), 當A跟B都是或都是1,結果...
- 4BitArray.Xor(BitArray) 方法(System.Collections) | Microsoft Docs
C# 複製. public System.Collections.BitArray Xor (System.Collections.BitArray value); ... 下列程式碼範例示範如...
- 5【c#】XOR運運算元 - 程式人生
請用通俗的英語解釋一下什麼是xor( ^ )運算子,它在下面的程式碼中是做什麼的: public int GetHashCode(Box bx) { int hCode = bx.Height ...