"Specified cast is not valid" only on release build from MS build

.net, c#, il, msbuild, visual-studio

Solution

It is likely that the call stack is different than what you are expecting it to be. Your method may be getting inlined, then `GetFrame(1)` is retrieving the caller's caller. When the value is retrieved from the dictionary, it is of a different type because it is for a different method.

You could try adding the attribute `[MethodImpl(MethodImplOptions.NoInlining]` to `SetAndGet` to prevent the inlining optimization for the method.

Problem

I am getting a "Specified cast is not valid" valid when doing only a release build from MSBuild 4.0. I tested this out in using a release build from Visual Studio 2012 and didn't get this issue. I also tested this out using a debug build from MSBuild 4.0 and didn't get this issue. Exception: Code ``` public abstract class CachedSessionBase : ISessionObject { protected Dictionary<MethodBase, Object> _getAndSetCache = new Dictionary<MethodBase, object>(); protected TResult SetAndGet<TResult>(ObjectFactory factory, Func<TResult> func) { StackTrace stackTrace = new StackTrace(); var methodBase = stackTrace.GetFrame(1).GetMethod(); if (!_getAndSetCache.ContainsKey(methodBase)) { _getAndSetCache[methodBase] = func.Invoke(); } return (TResult)_getAndSetCache[methodBase]; } ``` The error is being thrown on this line ``` return (TResult)_getAndSetCache[methodBase]; ```

Original source