csharpsquid:S2743 Static fields should not be used in generic types on lock object

I am getting csharpsquid:S2743 on a lock object in a generic singleton class. I think this use case is valid and should be marked as an exception to the rule. The current example exception scenario for the rule cannot be used as in general you don’t want to use a usable object as the lock object, that’s why you create an unused lock object of type object.

Example:

using System.Collections.Generic;

namespace Stryker.Core.Initialisation
{
    public class FolderCompositeCache<T>
    {
        private FolderCompositeCache()
        {

        }

        private static FolderCompositeCache<T> _instance;
        private static readonly object _lockObj = new object();

        public static FolderCompositeCache<T> Instance
        {
            get
            {
                lock (_lockObj)
                {
                    if (_instance == null)
                    {
                        _instance = new FolderCompositeCache<T>();
                    }

                    return _instance;
                }
            }
        }

        public Dictionary<string, T> Cache { get; set; }
    }
}

Hi @Rouke.Broersma.IS

thanks for the feedback. I can confirm the false positive.

You can follow the progress here: https://github.com/SonarSource/sonar-dotnet/issues/3839

1 Like