Search code examples
c#unity-game-enginewarningspragma

Pragma to disable warning causing another warning (CS1692)


I've the following snippet of code in one of my C# classes:

    public override int GetHashCode()
    {
        // Thanks: https://stackoverflow.com/a/5910237

        if (set == null) return 0;

        int h = 0x14345843;

        foreach (T elem in set)
        {
            h = unchecked(h + set.Comparer.GetHashCode(elem));
        }

        return h;
    }

With this code, I'll receive a warning: "Non-readonly field referenced in 'GetHashCode()'".

As that is intended in this case, I added the following pragma to dismiss that warning: #pragma warning disable RECS0025.

However, after adding that pragma, I received a new warning only in the Unity Editor - not when building the code in Visual Studio:

warning CS1692: Invalid number

Double-clicking it would take me straight to that #pragma warning disable RECS0025 line.

What am I doing wrong here? The goal is to suppress the RECS0025 warning, of course without causing another warning.

Extra: I tried disabling the CS1692 warning around the RECS0025 pragmas, but that didn't work either; the CS1692 error continued occurring.

Extra extra: I've some code elsewhere as follows:

#pragma warning disable RECS0108
    static SharedPool<Tuple<HierarchyMember, string>, ReactiveProperty<T>> _sharedPool;
#pragma warning restore RECS0108

This does not cause the CS1692 error to occur. That is, if I remove the #pragma warning disable RECS0025 from around the GetHashCode function, but leave the above RECS0108 pragma in, there will be no CS1692 warning.

Not sure how this adds up with the two provided answers.


Solution

  • That's due to the non-numeric prefix. I'm guessing Unity is using an old compiler or not the most recent spec of C#? I'm not familiar with the Unity compiler at all, but this should fix it.

    Be aware this disables all warnings, so I'd limit it in scope as much as possible.

    public override int GetHashCode()
    {
        // Thanks: https://stackoverflow.com/a/5910237
    #pragma warning disable
        if (set == null) return 0;
    
        int h = 0x14345843;
    
        foreach (T elem in set)
        {
            h = unchecked(h + set.Comparer.GetHashCode(elem));
        }
    
        return h;
    #pragma warning restore
    }