c# - string null checking from different style -
i don't know before asked or not, confuse in below of code block.
code 1
if (string.isnullorempty(control.text.trim())) { // code execute } code 2
if (control.text.trim() == "") { // code execute } code 3
if (control.text.trim() == null) { // code execute } code 4
if (control.text.trim() == string.empty) { // code execute } according me working me.
i feeling wonder different in between in 4 code block.
let's start primitives:
the first block checks if string control.text.trim() null or string.empty.
the second block checks if string control.text.trim() "".
the third block checks if string control.text.trim() null.
the fourth block checks if string control.text.trim() string.empty; same second block: "" equals string.empty.
fine, that's easy understand. however, note string.trim() never return null. thus, first block equivalent control.text.trim() == string.empty. same second block , fourth block, again because "" equals string.empty. third block never hit, ever.
thus, first, second , fourth blocks equivalent checking if control.trim empty string , third block useless , impossible satisfy. careful, if control null or control.text null hit exception. thus, should consider using `string.isnullorwhitespace , replacing with:
if(control != null && string.isnullorwhitespace(control.text)) { // code execute } (unless have sort of guarantee control not null, in case leave off first part of if).
Comments
Post a Comment