tags:

views:

92

answers:

2

When I compile a project with release build and code optimization types that are not referenced anywhere in code are no longer included in the assembly.

The problem is that I want to use these types by reflection at runtime.

Is there an attribute, or some other way that I can tell the compiler not to optimize away a given class?

+1  A: 

Are you using some sort of obfuscator or optimiser (e.g. Dotfuscator) that could be removing the types because it thinks they are unused? If so, you will have to configure that software so that it doesn’t remove them. That is not a C# compiler issue.

Otherwise, I have never seen this myself. All the types are always present in the assembly, even if they are not referenced. Anything else would be nuts because it would make Reflection really useless as you noticed.

So to test this, I just compiled a small project with two unused classes, and one class that is only used by one of the unused classes. None of them got removed, even in Release mode and even with “optimizations” enabled.

If you can provide a small example where the compiler does remove a type, it would probably be a compiler bug and you should perhaps consider reporting it to connect.microsoft.com.

Timwi
You are correct, The types I was looking for were in another namespace I hadn't noticed in reflector :). It seems that my issue is something else, I am using some static methods from within the class that is only used by reflection, perhaps that is the issue.
Andronicus
the offending code I discovered was Assembly.GetCallingAssembly().GetTypes(), which assumed that the calling assembly would contain the expected types. However, in release mode the actual calling assembly was "Anonymously Hosted DynamicMethods Assembly"
Andronicus
A: 

Here is a direct documentation about your disable/enable optimization concern:

http://msdn.microsoft.com/en-us/library/t0hfscdc%28v=VS.100%29.aspx

However, I've also found it strange that some codes aren't included in the assembly because of optimization.

Musa Hafalır
The `/optimize` flag is relevant only to the generated IL. It does not remove any types, members, or other metadata.
Timwi