Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with a C# conditional statement dealing with Strings

In my attempt at dissecting a bit of C# I am afraid I do not understand either the goal or the logic of this bit of code:

if (!string.IsNullOrEmpty(str2) && (Strings.UCase(Strings.Left(str2, 1)) != Strings.Left(str2, 1)))
    {
        return false;
    }

I understand the first part is checking if str2 is "not null", however the second part is coming off a bit flaky. So we UCase the first character of str2, and if it does not equal the first character of str2 (which is NOT "UCase"d), then return "false"?

Maybe I am not missing anything and what I described above is in fact what the code is doing. If this is the case, can we reform this into something else that offers the same result,say for example, check if str2 is uppercase or not? I feel like this is the end goal.

You thoughts?

like image 634
JohnZaj Avatar asked Jun 24 '26 23:06

JohnZaj


1 Answers

Yes, you understood the code right.

It looks like something translated from VB using a translation tool, as it's using functions from the VisualBasic namespace. I would rather write it with String methods:

if (!String.IsNullOrEmpty(str2) && str2.Substring(0,1).ToUpper() != str2.SubString(0,1)) {
  return false;
}

Or simply getting the first character as a character instead of as a string, and use the IsLower method of the Char class:

if (!string.IsNullOrEmpty(str2) && Char.IsLower(str2[0])) {
  return false;
}
like image 83
Guffa Avatar answered Jun 27 '26 13:06

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!