Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: better way than to combine StartsWith and two ToUpperInvariant calls

Tags:

c#

Somewhere in the back of my head a tiny voice is telling me "the C# code below smells".

private const string STR_ConnectionString = "ConnectionString";
private readonly string upperCaseConnectionString = STR_ConnectionString.ToUpperInvariant();
// a lot further on
string keyAttributeValue = keyAttribute.Value;
if (keyAttributeValue.ToUpperInvariant().StartsWith(upperCaseConnectionString)) 
{
    // some C# code handling a key that starts with "ConnectionString"
}

The constant STR_ConnectionString is used in other places in the code as well.

How to get rid of the smell?

like image 810
Jeroen Wiert Pluimers Avatar asked Jan 09 '12 13:01

Jeroen Wiert Pluimers


3 Answers

You can use the overloaded StartsWith method taking a StringComparison enum value:

keyAttributeValue.StartsWith(STR_ConnectionString, StringComparison.OrdinalIgnoreCase) // or use StringComparison.InvariantCultureIgnoreCase here
like image 124
Rich O'Kelly Avatar answered Sep 21 '22 22:09

Rich O'Kelly


There is a StartsWith overload which supports case-insensitive matching:

if (keyAttributeValue.StartsWith(STR_ConnectionString, 
                                 StringComparison.InvariantCultureIgnoreCase)
{
    ...
}

It also makes your code more readable, because it expresses your intention: What you really want is a case-insensitive comparison, and that's what's written here. You don't really want "a case-sensitive comparison of values converted to upper-case"... that's just the workaround you use to achieve the goal.

like image 27
Heinzi Avatar answered Sep 19 '22 22:09

Heinzi


If it smells bad because you're doing the ToUpper then the string compare, those can be combined using an overload of startswith:

STR_ConnectionString..StartsWith(upperCaseConnectionString, StringComparison.CurrentCultureIgnoreCase);

However, it looks like you're rolling your own way to handle application configuration, which you shouldn't do. See http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

like image 28
Arbiter Avatar answered Sep 19 '22 22:09

Arbiter