CA2002 warning on string[]

175 views Asked by At

Here is a class that, when compiled with Microsoft's minimum recommended code analysis rules, causes this warning:

CA2002 : Microsoft.Reliability : 'TestClass.SomeProperty.get()' locks on a reference of type 'string[]'. Replace this with a lock against an object with strong-identity.

public sealed class TestClass
{
    public TestClass(string[] first, string[] second)
    {
        combinedStrings = Combined(first, second);
    }

    public string SomeProperty
    {
        get
        {
            lock (combinedStrings)
                return "A string";
        }
    }

    private readonly string[] combinedStrings;

    private static string[] Combined(string[] first, string[] second)
    {
        var combined = new string[first.Length + second.Length];

        first.CopyTo(combined, 0);
        second.CopyTo(combined, first.Length);

        return combined;
    }
}

Why would a string array be considered a weak identity type? It's not like arrays get interned or something, do they? And even if they could be, I'm not locking on a statically defined one; it's dynamically constructed at run-time so guaranteed to be unique.

This is on Visual Studio 2010, if it makes a difference.

1

There are 1 answers

2
Patrick Hofman On

According to MSDN:

An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object.

The following types have a weak identity and are flagged by the rule:

  • ...

  • String

So the problem here is not the array, but the string type used. I would always opt to use an object as lock type. You can do that by creating a new object:

private object lockObject = new object();
public string SomeProperty
{
    get
    {
        lock (lockObject)
            return "A string";
    }
}