Skip to content

C#: Use HTTPS for MSDN qhelp links - #23246

Open
cjyhjy wants to merge 1 commit into
github:mainfrom
cjyhjy:csharp/https-msdn-links-5163
Open

cjyhjy wants to merge 1 commit into
github:mainfrom
cjyhjy:csharp/https-msdn-links-5163

Conversation

@cjyhjy

@cjyhjy cjyhjy commented Nov 25, 2026 •

Copy link
Copy Markdown

Summary

  • switch the remaining MSDN links under csharp/ql/src/Likely Bugs from HTTP to HTTPS
  • keep link targets and query-help text unchanged

Related to #5163. This PR addresses only the C# Likely Bugs MSDN-link subset and is not intended to close the umbrella issue.

Validation

  • git diff --check
  • fetched all 18 updated URLs with redirects enabled; every target returned HTTP 200
  • confirmed no http://msdn.microsoft.com links remain under csharp/ql/src/Likely Bugs

AI assistance: OpenAI Codex was used to identify the scoped link set and prepare the mechanical changes. The agent checked the resulting diff and verified every updated URL with automated HTTP requests. A maintainer review is recorded separately in the pull request review history.

@cjyhjy
cjyhjy requested a review from a team as a code owner November 25, 2026 15:36
Copilot AI adaptive review requested due to automatic review settings November 25, 2026 15:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the scoped documentation-only HTTPS link updates.

No open issues 🎉

What changed in this PR

Updates the remaining MSDN links in C# query-help documentation under csharp/ql/src/Likely Bugs from HTTP to HTTPS while preserving their targets and surrounding text.

Changes:

  • Converted 18 MSDN URLs across 16 .qhelp files to HTTPS.
  • Preserved URL paths, query parameters, link text, and documentation content.
  • Confirmed no http://msdn.microsoft.com links remain in the scoped directory.
File Description
csharp/​ql/​src/​Likely Bugs/​StaticFieldWrittenByInstance.qhelp Updated the static reference link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​Statements/​UseBraces.qhelp Updated the if-else reference link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​ReferenceEqualsOnValueTypes.qhelp Updated the Object.ReferenceEquals link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​RecursiveOperatorEquals.qhelp Updated the operator-overloading guidance link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​RandomUsedOnce.qhelp Updated the Random constructor link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​ObjectComparison.qhelp Updated the equality operator link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​NestedLoopsSameVariable.qhelp Updated the for reference link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​InconsistentCompareTo.qhelp Updated both MSDN reference links to HTTPS.
csharp/​ql/​src/​Likely Bugs/​IncomparableEquals.qhelp Updated the Object.Equals link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​HashedButNoHash.qhelp Updated the Object.GetHashCode link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​EqualsUsesIs.qhelp Updated the Object.Equals link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​EqualsUsesAs.qhelp Updated the Object.Equals link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​EqualsArray.qhelp Updated the SequenceEqual link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​Dynamic/​BadDynamicCall.qhelp Updated the dynamic reference link to HTTPS.
csharp/​ql/​src/​Likely Bugs/​DangerousNonShortCircuitLogic.qhelp Updated both operator reference links to HTTPS.
csharp/​ql/​src/​Likely Bugs/​BadCheckOdd.qhelp Updated the modulo operator link to HTTPS.

Review effort: Lite (adaptive)

@hvitved hvitved left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

@github-actions

Copy link
Copy Markdown
Contributor

QHelp previews:

csharp/ql/src/Likely Bugs/BadCheckOdd.qhelp

Bad parity check

Avoid using x % 2 == 1 or x % 2 > 0 to check whether a number x is odd, or x % 2 != 1 to check whether it is even. Such code does not work for negative numbers. For example, -5 % 2 equals -1, not 1.

Recommendation

Consider using x % 2 != 0 to check for odd and x % 2 == 0 to check for even.

Example

-9 is an odd number but this example does not detect it as one. This is because -9 % 2 is -1, not 1.

class CheckOdd
{
    private static bool IsOdd(int x)
    {
        return x % 2 == 1;
    }

    public static void Main(String[] args)
    {
        Console.Out.WriteLine(IsOdd(-9)); // prints False
    }
}

It would be better to check if the number is even and then invert that check.

class CheckOdd
{
    private static bool IsOdd(int x)
    {
        return x % 2 != 0;
    }

    public static void Main(String[] args)
    {
        Console.Out.WriteLine(IsOdd(-9)); // prints True
    }
}

References

csharp/ql/src/Likely Bugs/DangerousNonShortCircuitLogic.qhelp

Potentially dangerous use of non-short-circuit logic

The | and & logical operators, known as non-short circuit operators, should not be used. Using a non-short circuit operator reduces the efficiency of the program, is potentially confusing and can even lead to the program crashing if the first operand acts as a safety check for the second.

Recommendation

If the non-short circuit operator is unintended then replace the operator with the short circuit equivalent. Sometime a non-short circuit operator is required because the operands have side effects. In this case it is more efficient to evaluate both operands separately and then use a short circuit operator to combine the results.

Example

This example will crash because both parts of the conditional expression will be evaluated even if a is null.

class DangerousNonShortCircuitLogic
{
    public static void Main(string[] args)
    {
        string a = null;
        if (a != null & a.ToLower() == "hello world")
        {
            Console.WriteLine("The string said hello world.");
        }
    }
}

The example is easily fixed by using the short circuit AND operator. The program produces no output but does not crash, unlike the previous example.

class DangerousNonShortCircuitLogicFix
{
    public static void Main(string[] args)
    {
        string a = null;
        if (a != null && a.ToLower() == "hello world")
        {
            Console.WriteLine("The string said hello world.");
        }
    }
}

References

csharp/ql/src/Likely Bugs/Dynamic/BadDynamicCall.qhelp

Bad dynamic call

Method calls on variables declared with type 'dynamic' are resolved at runtime rather than compile-time - the actual type of the instance is determined, and an attempt is made to call a method on that type with the appropriate signature. If such a method does not exist, a RuntimeBinderException is thrown.

This rule identifies calls to instances with the dynamic type where it can be statically determined that the call will throw a RuntimeBinderException.

Recommendation

Ensure it is not possible to make a call to a dynamic instance of a type that lacks the appropriate method signature for handling that call.

Example

In this example the program attempts to call Foo on a class that doesn't have a Foo method. This program is guaranteed to fail at runtime with a RuntimeBinderException.

class BadDynamicCall
{
    class WithFoo
    {
        public void Foo(int i) { }
    }

    class WithoutFoo { }

    public static void Main(string[] args)
    {
        dynamic o = new WithoutFoo();
        o.Foo(3);
    }
}

References

csharp/ql/src/Likely Bugs/EqualsArray.qhelp

Equals on collections

There are some circumstances where you want to compare two arrays or collections using reference equality, but often you will want a deep comparison instead (that is, one that compares two collections on an element-by-element basis).

Recommendation

If you intended to make a deep comparison then the solution depends on whether or not you are using C# 3.5 or later. From C# 3.5 onward LINQ is available and you can replace the call to Equals with a call to the LINQ extension method SequenceEqual. If this is not possible then you can implement a helper function to compare arrays, which can then be used throughout your code.

Example

This example outputs "False" because calling Equals on an array only does a reference comparison.

class EqualsArray
{
    public static void Main(string[] args)
    {
        string[] strings = { "hello", "world" };
        string[] moreStrings = { "hello", "world" };
        Console.WriteLine(strings.Equals(moreStrings));
    }
}

The following example outputs "True" twice and uses two different methods of performing a deep comparison of the array.

class EqualsArrayFix
{
    static bool DeepEquals<T>(T[] arr1, T[] arr2)
    {
        // If arr1 and arr2 refer to the same array, they are trivially equal.
        if (ReferenceEquals(arr1, arr2)) return true;

        // If either arr1 or arr2 is null and they are not both null (see the previous
        // check), they are not equal.
        if (arr1 == null || arr2 == null) return false;

        // If both arrays are non-null but have different lengths, they are not equal.
        if (arr1.Length != arr2.Length) return false;

        // Failing which, do an element-by-element compare.
        for (int i = 0; i < arr1.Length; ++i)
        {
            // Early out if we find corresponding array elements that are not equal.
            if (!arr1[i].Equals(arr2[i])) return false;
        }

        // If we get here, all of the corresponding array elements were equal, so the
        // arrays are equal.
        return true;
    }

    public static void Main(string[] args)
    {
        string[] strings = { "hello", "world" };
        string[] moreStrings = { "hello", "world" };
        Console.WriteLine(strings.SequenceEqual(moreStrings));
        Console.WriteLine(DeepEquals(strings, moreStrings));
    }
}

References

csharp/ql/src/Likely Bugs/EqualsUsesAs.qhelp

Equals should not apply "as"

The method signature of Equals takes an object as an argument. It is therefore common to test whether the parameter is of the same type as the object that Equals is being called on. This should not be done using as and then checking for null because this technique does not limit the argument to being the exact same type as the object. It will not return null if the argument is a subtype of the object's type.

As an exception to the rule, it is acceptable to use as when your class is sealed, because the concern about subclassing does not then apply. That said, it is probably best to avoid it even then, because sealed classes can sometimes become unsealed later - it's sensible to try and avoid potential problems down the line.

Recommendation

Call GetType() on the argument and compare it with the type of the current object instead.

Example

The following example clearly demonstrates the problem with using as. The example outputs:

b does equal d.
d does not equal b.

This asymmetry violates the contract of the Equals method.

class EqualsUsesAs
{
    class BaseClass
    {
        public override bool Equals(object obj)
        {
            BaseClass objBase = obj as BaseClass;
            return objD != null;
        }
    }

    class DClass : BaseClass
    {
        public override bool Equals(object obj)
        {
            DClass objD = obj as DClass;
            return objD != null;
        }
    }

    public static void Main(string[] args)
    {
        BaseClass b = new BaseClass();
        DClass d = new DClass();
        Console.WriteLine("b " + (b.Equals(d) ? "does" : "does not") + " equal d.");
        Console.WriteLine("d " + (d.Equals(b) ? "does" : "does not") + " equal b.");
    }
}

References

csharp/ql/src/Likely Bugs/EqualsUsesIs.qhelp

Equals should not apply "is"

The method signature of Equals takes an object as an argument. It is therefore common to test whether the parameter is of the same type as the object that Equals is being called on. This should not be done using is because this technique does not limit the argument to being the exact same type as the object. It will not return false if the argument is a subtype of the object's type.

As an exception to the rule, it is acceptable to use is when your class is sealed, because the concern about subclassing does not then apply. That said, it is probably best to avoid it even then, because sealed classes can sometimes become unsealed later - it's sensible to try and avoid potential problems down the line.

Recommendation

Call GetType() on the argument and compare it with the type of the current object instead.

Example

The following example clearly demonstrates the problem with using is. The example outputs:

b does equal d.
d does not equal b.

This asymmetry violates the contract of the Equals method.

class EqualsUsesIs
{
    class BaseClass
    {
        public override bool Equals(object obj)
        {
            return obj is BaseClass;
        }
    }

    class DClass : BaseClass
    {
        public override bool Equals(object obj)
        {
            return obj is DClass;
        }
    }

    public static void Main(string[] args)
    {
        BaseClass b = new BaseClass();
        DClass d = new DClass();
        Console.WriteLine("b " + (b.Equals(d) ? "does" : "does not") + " equal d.");
        Console.WriteLine("d " + (d.Equals(b) ? "does" : "does not") + " equal b.");
    }
}

References

csharp/ql/src/Likely Bugs/HashedButNoHash.qhelp

Hashed value without GetHashCode definition

Classes that override System.Object.Equals() but not System.Object.GetHashCode() can yield unexpected results if instances of those classes are stored in a hashing data structure.

Recommendation

Override the GetHashCode method such that for two instances a and b, where a.Equals(b) is true, a.GetHashCode() and b.GetHashCode() are equal. The C# documentation states [1]:

If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two objects do not have to return different values.

Example

using System;
using System.Collections;

class Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(Object other)
    {
        Point point = other as Point;
        if (point == null)
        {
            return false;
        }
        return this.x == point.x && this.y == point.y;
    }

    public static void Main(string[] args)
    {
        Hashtable hashtable = new Hashtable();
        hashtable[new Point(5, 4)] = "A point"; // BAD
        // Point overrides the Equals method but not GetHashCode.
        // As such it is probably not useful to use one as the key for a Hashtable.
        Console.WriteLine(hashtable[new Point(5, 4)]);
    }
}

References

csharp/ql/src/Likely Bugs/IncomparableEquals.qhelp

Equals on incomparable types

Calling x.Equals(y) on incomparable types will almost always return false. If two classes do not have a common parent class their instances are considered incomparable.

Recommendation

Carefully check the code for errors.

Example

In this example both calls to the Equals method will always return false regardless of the contents of the ArrayList or String because ArrayLists and Strings are incomparable.

using System.Collections;

class IncomparableEquals
{
    public static void Main(string[] args)
    {
        ArrayList apple = new ArrayList();
        String orange = "foo";
        Console.WriteLine(apple.Equals(orange)); // BAD
        Console.WriteLine(orange.Equals(apple)); // BAD
    }
}

References

csharp/ql/src/Likely Bugs/InconsistentCompareTo.qhelp

Inconsistent CompareTo and Equals

When an ordering is introduced on instances of a class by making the class implement the IComparable interface, it is sensible to ensure that for all instances c1 and c2, c1.CompareTo(c2) == 0 ⇔ c1.Equals(c2). Classes that implement IComparable.CompareTo but inherit Equals, rather than overriding it to match the CompareTo implementation, generally violate this assumption, which can lead to confusion when the class is used.

If the type implements IComparable, it should override Equals.

- Microsoft: Guidelines for Overloading Equals() and Operator ==

Recommendation

A class that implements CompareTo should generally also override Equals in order to provide a consistent implementation.

Example

The following example outputs:

Comparing a1 with a2: 0
a1 equals a2: False

This is obviously not desirable as shows an inconsistency between the behavior of CompareTo and the behavior of Equals.

class InconsistentCompareTo
{
    class Age : IComparable<Age>
    {
        private int age;
        public Age(int age)
        {
            this.age = age;
        }
        public int CompareTo(Age rhs)
        {
            return age.CompareTo(rhs.age);
        }
    }

    public static void Main(string[] args)
    {
        Age a1 = new Age(22);
        Age a2 = new Age(22);
        Console.WriteLine("Comparing a1 with a2: " + a1.CompareTo(a2));
        Console.WriteLine("a1 equals a2: " + a1.Equals(a2));
    }
}

References

csharp/ql/src/Likely Bugs/NestedLoopsSameVariable.qhelp

Nested loops with same variable

Inner loops should not write to the iteration variables of the enclosing loop. If an inner loop changes the iteration variable of the enclosing loop this is normally because the programmer mistyped the iteration variable of the inner loop. If this is the intended behavior, then this is an example of bad practice. Loops should be designed so that each loop controls its own iteration. Nested loops where iteration is shared between loops are more difficult to understand and maintain.

Recommendation

If there is a mistake in the code then correct it. If the behavior is intended then consider redesigning the way that iteration of the loops is controlled. This will make the code easier for other programmers to understand and maintain.

Example

This example will run forever because the inner loop increments i instead of j.

class NestedLoopsSameVariable
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 2; i++)
            {
                Console.WriteLine(i + " " + j);
            }
        }
    }
}

References

csharp/ql/src/Likely Bugs/ObjectComparison.qhelp

Reference equality test on System.Object

If one or both operands of a comparison have the compile type System.Object or interface type, a reference comparison will be performed. This is often not what is wanted, especially when the runtime type of one of the operands declares operator==.

It should be noted that an exception is made for comparisons to read-only constants - a reference comparison is more likely to be intentional in such cases.

Recommendation

Ensure a reference comparison is really the correct comparison to perform. If it is not then choose a more appropriate comparison. If reference comparison is intended, use ReferenceEquals instead for clarity.

Example

In this example the console will output "False" because a reference comparison is performed instead of using the == operator overloaded in AlwaysEqual.

class ObjectComparison
{
    class AlwaysEqual
    {
        public static bool operator ==(AlwaysEqual a, AlwaysEqual b)
        {
            return true;
        }
        public static bool operator !=(AlwaysEqual a, AlwaysEqual b)
        {
            return false;
        }
    }
    public static void Main(string[] args)
    {
        object a = new AlwaysEqual();
        AlwaysEqual b = new AlwaysEqual();
        Console.WriteLine(a == b);
    }
}

References

csharp/ql/src/Likely Bugs/RandomUsedOnce.qhelp

Random used only once

A program that uses System.Random to generate a sequence of pseudo-random numbers should not create a new instance of Random every time a new pseudo-random number is required (for example, new Random().Next()).

According to MSDN:

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers.

The sequence of pseudo-random numbers returned by these calls depends only on the value of the seed. If you construct a new Random object each time a pseudo-random number is needed, this does not generate a good distribution of pseudo-random numbers, even though the parameterless Random() constructor tries to initialize itself with a unique seed.

Recommendation

Create a Random object once and use the same instance when generating sequences of pseudo-random numbers (by calling Next, NextBytes or NextDouble).

Example

In the first example, the same number is actually output ten times, because the random number generator is initialized with the same time value.

using System;

class BadRandom
{
    public static void Main(string[] args)
    {
        for (int i = 0; i < 10; ++i)
            Console.Out.WriteLine(new Random().Next());

        /* Typical output:
                1003050238
                1003050238
                1003050238
                1003050238
                1003050238
                1003050238
                1003050238
                1003050238
                1003050238
                1003050238
        */
    }
}

This is fixed by using a single Random instance to guarantee a good distribution.

using System;

class FixedRandom
{
    public static void Main(string[] args)
    {
        Random rng = new Random();
        for (int i = 0; i < 10; ++i)
            Console.Out.WriteLine(rng.Next());

        /* Typical output:
                1727678897
                1302766072
                1862602754
                306287288
                1158341977
                1381161104
                1200326172
                1743307709
                611422858
                1455448871
        */
    }
}

References

csharp/ql/src/Likely Bugs/RecursiveOperatorEquals.qhelp

Recursive call to operator==

When writing an operator==, it is common to want to check whether or not an operand is null or check if both operands refer to the same object. Attempting to do this using == will not work as it will simply call the overridden operator== that is being defined.

Recommendation

There are two suggested ways to fix the problem. The tidiest approach is to simply replace the call to operator== with a call to ReferenceEquals (see code below). As a less preferable alternative, it is also possible to simply cast the parameters to object .

Example

In this example the == overload will constantly call itself to compare the initial arguments passed to it with null.

class Year
{
    private int year;
    private bool bc;

    public Year(int i)
    {
        year = Math.Abs(i);
        bc = i < 0;
    }

    public static bool operator ==(Year lhs, Year rhs)
    {
        // Both of these checks against null call operator== recursively.
        // They were probably intended to be checks for reference equality.
        if (lhs == null || rhs == null)
        {
            return false;
        }

        return lhs.year == rhs.year && lhs.bc == rhs.bc;
    }

    public static bool operator !=(Year lhs, Year rhs)
    {
        return !(lhs == rhs);
    }
}

The best fix is to use the ReferenceEquals method instead.

class Year
{
    private int year;
    private bool bc;

    public Year(int i)
    {
        year = Math.Abs(i);
        bc = i < 0;
    }

    public static bool operator ==(Year lhs, Year rhs)
    {
        // Either of these alternative approaches works.
        if (ReferenceEquals(lhs, null) || (object)rhs == null)
        {
            return false;
        }

        return lhs.year == rhs.year && lhs.bc == rhs.bc;
    }

    public static bool operator !=(Year lhs, Year rhs)
    {
        return !(lhs == rhs);
    }
}

References

csharp/ql/src/Likely Bugs/ReferenceEqualsOnValueTypes.qhelp

Call to ReferenceEquals(...) on value type expressions

The Object.ReferenceEquals(...) method is used to determine if two objects are the same instance. Since the method takes two objects as parameters, value types will automatically be boxed in different objects when calling the method. Hence, the method ReferenceEquals(..) will always return false when comparing value type expressions, including struct values. As such, this kind of check is at best useless and at worst erroneous.

Recommendation

Consider whether the equality test is needed. If it is not then remove it, otherwise replace it with a more appropriate equality check such as ==.

Example

In this example, the programmer is attempting to compare two ints but since they are value types the ReferenceEquals method will always return false. They should really be compared using i == j.

class ReferenceEqualsOnValueTypes
{
    static void Main(string[] args)
    {
        int i = 17;
        int j = 17;

        bool b = ReferenceEquals(i, j);
    }
}

References

csharp/ql/src/Likely Bugs/Statements/UseBraces.qhelp

Misleading indentation

A control structure (if statements and loops) has a body that is either a block of statements or a single statement. The second option may be indicated by omitting the braces: { and }.

However, omitting the braces can lead to confusion, especially if the indentation of the code suggests that multiple statements are within the body of a control structure when in fact they are not.

Recommendation

It is usually considered good practice to include braces for all control structures in C#. This is because it makes it easier to maintain the code later. For example, it's easy to see at a glance which part of the code is in the scope of an if statement, and adding more statements to the body of the if statement is less error-prone.

You should also ensure that the indentation of the code is consistent with the actual flow of control, so that it does not confuse programmers.

Example

In the example below, the if statement checks whether the item i is null before adding it to the list. However the if statement does not guard the call to Console.Out.WriteLine, resulting in a NullReferenceException whenever null is passed to the function AddItem.

void AddItem(Object i)
{
    if (i != null)
        items.Add(i);
    Console.Out.WriteLine("Item added: " + i.ToString());
}

This code is fixed by adding curly braces { and } around both statements, as shown below.

void AddItem(Object i)
{
    if (i != null)
    {
        items.Add(i);
        Console.Out.WriteLine("Item added: " + i.ToString());
    }
}

References

csharp/ql/src/Likely Bugs/StaticFieldWrittenByInstance.qhelp

Static field written by instance method

Static fields represent the shared state of all instances of a class. It is therefore bad practice to modify this state from any particular instance. Because static fields are shared between all instances of a class existing in all threads of a program, one instance trying to read the field while another tries to write it can lead to race conditions and hence mean the class is not thread safe. It also decreases readability as most developers expect instance methods to only affect the instance state and static methods to only affect the static state.

Recommendation

It is important to evaluate the situation carefully before implementing a fix for an alert of this rule. Perhaps the field is erroneously declared static, and should in fact be an instance field; if so, then remove the static modifier from the field. If the field genuinely has to be static, evaluate the assumptions behind the code. Does it really have to be modified directly in an instance method? It could be helpful to wrap the accesses to the field in static methods, so that any concerns about synchronization can be addressed while avoiding code duplication.

Example

In this example the field called "name" has been mistakenly declared static. Attempting to rename a person will actually modify the static name field and affect all people.

public class Customer
{
    private static String name;
    public void rename(String newname)
    {
        name = newname; // BAD
    }
}

References

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants