C #: better than combining StartsWith and two calls ToUpperInvariant

Somewhere deep in my head, a tiny voice tells me that "the C # code smells lower."

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 STR_ConnectionString also used elsewhere in the code.

How to get rid of the smell?

+6
source share
5 answers

You can use the overloaded StartsWith method using the StringComparison enum value:

 keyAttributeValue.StartsWith(STR_ConnectionString, StringComparison.OrdinalIgnoreCase) // or use StringComparison.InvariantCultureIgnoreCase here 
+5
source

There is a StartsWith overload that supports case insensitivity:

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

It also makes your code more readable because it expresses your intention: what you really want is case-insensitive comparison and what is written here. You really do not want to "case-insensitively capitalize" ... this is just a workaround that you use to achieve the goal.

+4
source

If it smells bad because you are doing ToUpper, then comparing the strings, they can be combined using the startswith overload:

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

However, it looks like you are riding your own way of handling application configuration, which should not be done. See http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

+2
source

Is always

 keyAttributeValue.StartsWith(STR_ConnectionString, StringComparison.InvariantCultureIgnoreCase) 

but it will not work as good as what you have. If you need to do this thousands of times per second, stick to what you have. If not, just be case insensitive.

Also consider

 keyAttributeValue.StartsWith(STR_ConnectionString, StringComparison.OrdinalIgnoreCase) 

which is faster and probably you still want.

+2
source

I made an extension method that uses StringComparison to ignore the case, to handle this in my projects.

 public static string StartsWithIgnoreCase(this string value, string startsWith) { return value.StartsWith(value, StringComparison.InvariantCultureIgnoreCase); } 

You can add null checks if you want.

+1
source

Source: https://habr.com/ru/post/905519/


All Articles