Why do I get Code Analysis CA1062 on an out parameter in this code?
I have a very simple code (simplified from the original code - so I know it's not a very clever code) that when I compile in Visual Studio 2010 with Code Analysis gives me warning CA1062: Validate arguments of public methods.
public class Foo
{
protected static void Bar(out int[] x)
{
x = new int[1];
for (int i = 0; i != 1; ++i)
x[i] = 1;
}
}
The warning I get:
CA1062 : Microsoft.Design : In externally visible method 'Foo.Bar(out int[])', validate local variable '(*x)', which was reassigned from parameter 'x', before using it.
I don't understand why do I get this warning and how can I resolve it without suppressing it? Can new
return null
? Is this a Visual Studio 2010 bug?
UPDATE
I've decided to open a bug report 开发者_JAVA百科on Microsoft Connect.
I've reproduced this in Visual Studio 2010 Premium with the code exactly as given and with Microsoft All Rules enabled in the analysis settings.
It looks like this is a bug (see bottom of here: http://msdn.microsoft.com/en-us/library/ms182182.aspx). It is complainng that you are not checking that x
is not null before using it, but it's on out
parameter so there is no input value to check!
It's easier to show than to describe :
public class Program
{
protected static int[] testIntArray;
protected static void Bar(out int[] x)
{
x = new int[100];
for (int i = 0; i != 100; ++i)
{
Thread.Sleep(5);
x[i] = 1; // NullReferenceException
}
}
protected static void Work()
{
Bar(out testIntArray);
}
static void Main(string[] args)
{
var t1 = new Thread(Work);
t1.Start();
while (t1.ThreadState == ThreadState.Running)
{
testIntArray = null;
}
}
}
And the correct way is :
protected static void Bar(out int[] x)
{
var y = new int[100];
for (int i = 0; i != 100; ++i)
{
Thread.Sleep(5);
y[i] = 1;
}
x = y;
}
精彩评论