Question: 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: ![enter image description here](https://i.stack.imgur.com/S7p7T.png)

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];

```

Answer: 
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.
I had the same problem when running `nuget pack` which invoked 

> 
> MSBuild auto-detection: using msbuild version '15.0'...
> 
> 
> 

but the problem was solved by running `dotnet pack` which invoked

> 
> Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
> 
> 
>