Search code examples
c#visual-studio-2015string-comparisonfxcop

How to use the StringComparison in c# (CA1307)?


My aim is to omit the data which author_name starts with pipeline and author_email starts with pipeline@gmail.com If the project name starts with ej2 or Ej2.

I have below code. This code worked perfectly what I expected.

if ((author_name != "pipeline" && author_email != "pipeline@gmail.com") && 
    (projectName.StartsWith("ej2") == false || projectName.StartsWith("Ej2") == false))
{
  // some operations
}

My FxCop said to below violation to use the above method.

Severity Code Description Project File Line Suppression State Warning CA1307 Because the behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings, replace this call in 'GetProjectDetailsByApi.DevelopmentBranchStatus(List)' with a call to 'string.StartsWith(string, StringComparison)'. If the result of 'string.StartsWith(string, StringComparison)' will be displayed to the user, such as when sorting a list of items for display in a list box, specify 'StringComparison.CurrentCulture' or 'StringComparison.CurrentCultureIgnoreCase' as the 'StringComparison' parameter. If comparing case-insensitive identifiers, such as file paths, environment variables, or registry keys and values, specify 'StringComparison.OrdinalIgnoreCase'. Otherwise, if comparing case-sensitive identifiers, specify 'StringComparison.Ordinal'.

So I changed my code like below. But I got only

if (author_name.Equals("pipeline", StringComparison.OrdinalIgnoreCase) == false
    && author_email.Equals("pipeline@gmail.com", StringComparison.OrdinalIgnoreCase) == false 
    && projectName.StartsWith("ej2", StringComparison.OrdinalIgnoreCase) == false)
{
   //mY code
}

But above code filter all ej2 project. But I want to filter only the project which have the author_name and author_email is pipeline and pipeline@gmail.com respectively.

If I change the condition projectName.StartsWith("ej2", StringComparison.OrdinalIgnoreCase) == **true** means, It gives only the project which starts only ej2.

How can I do it?


Solution

  • If I understand you correctly, the problem is that you're doing a case-insensitive comparison on one string (ej2) instead of a case sensitive comparison (using StringComparison.Ordinal) on both strings (ej2 and Ej2) that you want to filter (at least that's the change I see from your first to the second condition).

    Something like this seems like a FxCop-safe version of your original condition (Note: I used the "not" operator (!) instead of == false to save some typing):

    if (!author_name.Equals("pipeline", StringComparison.OrdinalIgnoreCase)
        && !author_email.Equals("pipeline@gmail.com", StringComparison.OrdinalIgnoreCase)
        && !projectName.StartsWith("ej2", StringComparison.Ordinal) 
        && !projectName.StartsWith("Ej2", StringComparison.Ordinal))
    {
       // do something here...
    }