19

Does C# compiler (in VS2008 or VS2010) remove unused methods while compiling ?

I assume that it may have a problem deciding if public methods will ever be used, so I guess it will compile all the public methods.

But what about private methods that are never used inside a class ?

EDIT:

Are there a set of rules about the compiler's optmization that are documented anywhere ?

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185

4 Answers4

26

Just checked in reflector with a release build. The compiler doesn't remove the unused private methods.

There are ways to use a method without the compiler knowledge, like with reflection. So the compiler doesn't try to guess. It just leaves the methods there.

The only private methods the compiler removes are partial methods without implementation.

For the C# compiler optimizations, look here (archive.org).

jasper
  • 3,424
  • 1
  • 25
  • 46
Jordão
  • 55,340
  • 13
  • 112
  • 144
  • Is there a way to compile where the compiler _does_ throw away unused code? Use-case: I want to import _one_ function from a huge 3rd party library, and have the compiler not include everything? I think this is commonly done in JS/TS builds (tree shaking etc.). – Jeppe Mar 06 '22 at 09:52
8

The compiler doesn't strip any method from the assembly, public or private. I could in fact cause weird issues with reflection, and prevent runtime calls to such methods.

There are a lot of frameworks (like the XAML parser) which enable you to call private methods without static bindings (think about OnClick="myFunction" in a XAML file) This markup will call the potentially private myFunction when the OnClick event is raised... But the compiler has no informations about such a behavior at compile time.

Dynamic code suffer from the same issue, IL generation too. And you can access private methods from any object when executing under full trust.

Eilistraee
  • 8,220
  • 1
  • 27
  • 30
3

This optimization is effectively implemented at the JIT level, which is good because then it works for both public/private/whatever methods. If a method is never called (ignoring ngen, etc.), it never gets JITed. Now you might say that this is still a waste of space for metadata etc. but as others have pointed out, private isn't so private.

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78
  • I don't see how the optimization has value at the JIT level. The point of nuking the unused methods is to reduce the size of the binary. Once you're doing JITing the size of the binary no longer matters. – Billy ONeal Mar 05 '11 at 17:41
  • 2
    The size of the binary in memory matters too. – Logan Capaldo Mar 05 '11 at 19:39
2

No they won't be removed. It may give you warning for that but won't do it itself.

Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79