Question

I'm having problems with a piece of code that behaves differently depending on whether it was compiled in the Release or Debug configuration in Visual Studio. I have manually altered all the project compilation settings I can see on the Release config so that it matches the Debug one, but the problem persists.

The code (below) returns the Guid of the executing assembly:

private static Guid GetApplicationUid() 
{ 
   Assembly assembly = Assembly.GetCallingAssembly(); 
   GuidAttribute attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), false)[0]; 
   return new Guid(attribute.Value); 
}

The method fails with an "Index was outside the bounds of the array." exception when executed after compilation in Release mode. It works correctly in Debug mode. The reason this is that in this configuration, the assembly reference created by GetExecutingAssembly() is to a temporary assembly (eg. App_Web_eelfd0ff, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null) rather than the underlying "real" one.

Strangely enough, I have another component running in the same web that uses the same code and behaves the same regardless of the compilation mode.

Why is this happening and how to prevent it?

Was it helpful?

Solution

It's possible that when optimizations are enabled, the function is being inlined into a different assembly. Try adding MethodImplOptions.NoInlining, as per this answer so that the method is in the assembly you think it is.

OTHER TIPS

The exception means the assembly does not have a GUID attribute. At a guess, it may be optimized away by the compiler in release mode if the assembly is not set to be COM visible1. Check your other working assembly to see if it is registered for COM interop.

1GUID's are only used in .NET assemblies for COM interop. Visual Studio by automatically adds a GUID for you when you create a new project in case you want to do COM interop, but otherwise it is useless.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top