How to tell whether Code Access Security is allowed in library code
- by Sander Rijken
In .NET 4 Code Access Security (CAS) is deprecated. Whenever you call a method that implicitly uses it, it fails with a NotSupportedException, that can be resolved with a configuration switch that makes it fall back to the old behavior.
We have a common library that's used in both .NET 3.5 and .NET 4, so we need to be able to tell whether or not we should use the CAS method.
For example, in .NET 3.5 I should call:
Assembly.Load(string, Evidence);
Whereas in .NET 4 I want to call
Assembly.Load(string);
Calling Load(string, Evidence) throws a NotSupportedException.
Of course this works, but I'd like to know if there's a better method:
try
{
asm = Assembly.Load(someString, someEvidence);
}
catch(NotSupportedException)
{
asm = Assembly.Load(someString);
}