Search code examples
c#.netdisposeusing

Version-independent code for Rfc2898DeriveBytes (has Dispose on .NET 4.0 but not on 2.0)


I'm writing a small .NET 2.0 compatible assembly which uses Rfc2898DeriveBytes. On .NET 2.0 Rfc2898DeriveBytes does not implement IDisposable, while in .NET 4.0 Rfc2898DeriveBytes does implement IDisposable.

My assembly is loaded in .NET 4.0 applications and in .NET 2.0 applications.

Do I need to Dispose Rfc2898DeriveBytes using .NET 4.0 or can I just ignore it like with MemoryStream? If so, how can I write .NET 2.0 and .NET 4.0 compatible code, calling Dispose only on .NET 4.0? (At best without reflection and so on.)

I guess not using Dispose on that class is not dangerous because IDisposable comes from the abstract DeriveBytes-class.


Solution

  • You could:

    Rfc2898DeriveBytes rfc = null;
    
    try
    {
        var salt = new byte[128];
        rfc = new Rfc2898DeriveBytes("password", salt);
    }
    finally
    {
        IDisposable disp = rfc as IDisposable;
    
        if (disp != null)
        {
            disp.Dispose();
        }
    }
    

    even with Roslyn, the compiler doesn't remove the as IDisposable: http://goo.gl/OObkzv (right pane, it is already in Release mode, so with optimizations active)

    (note that I'm not exactly replication the using pattern... I have initialized the rfc variable inside the try/finally instead of outside... There is probably no practical difference)