How to get rid of CA2000 warning when ownership is transferred?
I also asked this at connect.microsoft.com and this is what they answered:
You can workaround the issue by having the container/collection object that adds the disposable object implement ICollection or ICollection<T>. The method that performs the Add must also have name starting with "Add".
And sure enough: when class Test implements ICollection<Item>, then the warning goes away. This is an acceptable solution for the case in question. But it's still an open question what to do, when it's not appropriate to implement ICollection to indicate transfer of ownership.
public sealed class Test: IDisposable, ICollection<Item>
{
public void Initialize()
{
var item1 = new Item(); // no warning
itemCollection.Add(item1);
var item2 = new Item(); // no warning
((ICollection<Item>)this).Add(item2);
var item3 = new Item(); // no warning
AddSomething(item3);
}
//... implement ICollection and Method AddSomething
}
Do you want to fix the code or just suppress the warnings? Suppressing the warnings is straightforward:
[SuppressMessage("Microsoft.Reliability",
"CA2000:DisposeObjectsBeforeLosingScope",
Justification = "Your reasons go here")]
public void Initialize()
{
// ...
}