remove unused code?

Jan 26, 2010 at 1:51 AM

could it automatically remove unused code so it could reduce the size of output assembly?

Jan 26, 2010 at 9:06 AM
Edited Jan 26, 2010 at 9:19 AM

Quick answer: no, it couldn't.

Although it seems great idea at first glance, removing unused code isn't safe. Consider the following program:

using System;
using System.Reflection;

class Program
	static void Main()

	static Action GetMethod(string method)
		var mi = typeof(Program).GetMethod(method);
		return (Action)Delegate.CreateDelegate(typeof(Action), null, mi);

	public void UnusedCode()
		Console.WriteLine("This method is never called");

Instance method UnusedCode is never referenced. In fact, class Program is never instanciated at all. Yet this this method is called.

In .NET one could not say that some code is "unused" because of reflection. So static analysis is not enough.


Jan 26, 2010 at 10:47 AM
right, your make your point. I did not thought of this problem. maybe
an option for user to choose to remove or not is better:)