JohnZaj
JohnZaj

Reputation: 3230

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?

Upvotes: 3

Views: 526

Answers (5)

BillW
BillW

Reputation: 3435

I share the perceptions you have when you say : "I do not understand either the goal or the logic of this bit of code" :) A test that returns only 'false is "fishy" : presumably "something" is waiting for a boolean to be returned, and nothing is returned if the result of this evaluates to 'true.

But if I had to write such a function I'd use the alternative OR logic :

return (! (String.IsNullOrEmpty(testString) || testString.ToUpper()[0] == testString[0]));

Upvotes: 0

eKek0
eKek0

Reputation: 23289

This is the same, but refactored:

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

It is clear that this code tests that the first letter of str2 is or isn't in uppercase when it has any character.

Upvotes: 0

Guffa
Guffa

Reputation: 700372

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;
}

Upvotes: 6

Shankar R10N
Shankar R10N

Reputation: 4966

Code Objective in English :)

If the non-empty string begins with a lower case character then return false

Upvotes: 3

Mark Brittingham
Mark Brittingham

Reputation: 28865

My bet is that they are really just testing whether the first character is uppercase. The initial "IsNullOrEmpty" test is just there to make sure that the real test doesn't throw an exception.

The big question: if there is no string value (null or empty) this will not return false. Is that the expected outcome?

Upvotes: 4

Related Questions