Jameel
Jameel

Reputation: 81

How to Add Custom Rule to FXCop for avoiding == operator inside the method

I want to add a Custom rule for avoiding the '==' operator inside a method in a class. For example in the below method i need to avoid 'str1==str2' with string.Compare(str1, str2,StringComparison.Ordinal);.So I need to check this types of code are appear in any of the method

public void StringTest2()
    {
        string str1 = "Hello";
        string str2 = "HELLO";
        if (str1 == str2)
        {
        }
    }

Upvotes: 0

Views: 274

Answers (2)

Jameel
Jameel

Reputation: 81

**The below code checks both the assignment and equal to operator in an assembly**


public override ProblemCollection Check(Member member)
            {
                var method = member as Method;
                if (method == null)
                    return null;
                if (method.Instructions.Count > 0)
                {
                    foreach (var instruction in method.Instructions)
                    {
                        if (instruction != null)
                            if ( instruction.OpCode == OpCode.Ceq)
                            {
                                var resolution = GetResolution(member.Name.Name);
                                var problem = new Problem(resolution, member)
                                                  {
                                                      Certainty = 95,
                                                      FixCategory = FixCategories.Breaking,
                                                      MessageLevel = MessageLevel.Warning
                                                  };
                                Problems.Add(problem);
                            }
                    }
                }
                return base.Problems;
            }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504172

Just say no.

The string == operator already performs an ordinal comparison, and is considerably more readable IMO than insisting on using string.Compare.

Even if you did want an ordinal string comparison explicitly, I'd suggest using string.Equals(string, string, StringComparison) instead of Compare.

Upvotes: 1

Related Questions