Single post

Checking to see if a string is uppercase in C#

As part of a work project I needed to check to see if a string was all upper-case (and act on it if it was).  I wondered if someone had already written something to do this, so had a quick Google for it.  All of the cases I found involved using regular expressions, checking to see if the source string matched [a-z]*.  That’s lovely and all, but it fails as soon as you encounter numbers or punctuation and so on.  Then I realised that, actually, it’s a very simple problem:

public static bool IsUppercase(this string str)
{
return string.Compare(str.ToUpper(), str, false) == 0;
}

 

paolo
February 19th, 2013 at 4:25 pm

Please fix your code, it’s useless to compare a string to its uppercase version if you pass “true” to the argument “ignoreCase”.
It should be:

public static bool IsUppercase(this string str)
{
return string.Compare(str.ToUpper(), str, false) == 0;
}

carl
February 19th, 2013 at 5:12 pm

Hah! Epic fail on my part. Good catch!

paolo
February 19th, 2013 at 7:50 pm

🙂

LEAVE A COMMENT

theme by teslathemes