Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Compiler optimization - Unused methods

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 ?

like image 804
Yochai Timmer Avatar asked Mar 05 '11 15:03

Yochai Timmer


2 Answers

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).

like image 165
Jordão Avatar answered Sep 18 '22 21:09

Jordão


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.

like image 28
Eilistraee Avatar answered Sep 21 '22 21:09

Eilistraee