Compare a nullable-int and a string for equality in C# -


i find reason compare 2 values or objects in c# - different types - , find myself unhappy code write.
code ends looking (to me) verbose , unclear , end feeling need add comment says "//check if they're equal".
(i blame fact that there's no nullsafe-dereference operator saw in groovy once.)

in recent example, have 2 variables:
string s;
int? i;

let's want compare them can if they're "obviously equal".
i'm defining them "obviously equal" if either:
a) int? doesn't contain number , string null, or else...
b) string you'd if wrote out numerical value of int? in plain / unformatted fashion.

[note in case i'm not bothered whether number 1234 considered equal strings "01234" or "1234.00" (or indeed "1234,00", if you're consider foreign).
can have flexibility either way on long "1234" is considered equal, , (e.g.) "1233+1" , "1234z" aren't.
can have flexibility on whether int? doesn't contain number considered equal empty string.]

so, want [clear / simple / short - apologies subjectiveness] expression put in "if" condition perform check required above , won't throw exception.
options?

(if wants compare solution how might more expressed in other languages, feel free. it's useful know greener grass is...)

update:

my own code boils down like...
if (s == (i.hasvalue ? i.value.tostring() : null))
doesn't bad s , aren't meaningfully named properties on other objects. [however, don't leaving "==" comparison in there because (though works strings because of string-interning and/or operator override or something) it's checking reference equality, right? i'd consider replacing string.equals... that's more horrible read.]

when have check parent objects (on "meaningful properties" exist) null, code gets long-winded - , that's on mind when posted question, think. wanted see whether else had missing.

i want able check positive condition , have else evaluate false (without throwing visible exception). so...

if ( (someobject.s == null && someother.i == null)
||
(int.parse(someobject.s) == someother.i) )

or similar very "happy" if possible (null-ref / parse) exceptions silently coerced false.
guess i'm getting lazy in old age....

    public static bool obviouslyequals<t>(this string  s, t? t) t: struct     {         if (s == null && !t.hasvalue)             return true;         if (s == null || !t.hasvalue)             return false;         return s.equals(t.value.tostring());     }   string s; int? i;  if (s.obviouslyequals(i))... 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -