Damian Hickey

Mostly software and .NET related. Mostly.

On ReSharper, object initializers, disposables and code analysis rule CA2000

Given a disposable class and a consumer:

public class DisposableClass : IDisposable
{
	public string Text { get; set; }

	public void Dispose()
	{}
}

public class Consumer
{
	public Consumer()
	{
		var disposableClass = new DisposableClass();
		disposableClass.Text = "S";
	}
}

ReSharper's quick fix will suggest to use object initializer:

Following this suggestion gives:

public class Consumer
{
	public Consumer()
	{
		var disposableClass = new DisposableClass { Text = "S" };
	}
}

But there is is a problem with this. If you run code analysis you will get the the following warning:

CA2000 : Microsoft.Reliability : In method 'Consumer.Consumer()', call System.IDisposable.Dispose on object '<>g__initLocal0' before all references to it are out of scope.

The problem is that under the hood, the compiler is creating a temporary local of DisposableClass, <>g_intLocal0, initializing it, then assigning it to variable disposableClass.

It's this local that it not getting disposed that causes the code analysis warning.

Perhaps the compiler could do a better job here but ReSharper could definitely do a better job:

  • Only suggest the object initializer quick fix for classes that are not disposable.
  • Include a quick fix to remove object initializers from disposable objects.

The issue has been reported, but infortunately JetBrains have marked it as "Won't Fix".

Edit 22/09/12: Looks like this will be fixed in Resharper 7.1.