Is your code running in a SharePoint Sandbox?
You could execute a function call that is not allowed in the sandbox (for example call a static method on SPSecurity) and catch the exception. A better approach is to test the friendly name of you app domain:
AppDomain.CurrentDomain.FriendlyName returns "Sandboxed Code Execution Partially Trusted Asp.net AppDomain"
Because you can never be sure that this string changes in the future, a safer approach will be:
AppDomain.CurrentDomain.FriendlyName.Contains("Sandbox")
See http://www.sharepointoverflow.com/questions/2051/how-to-check-if-code-is-running-as-sandboxed-solution for a discussion on this topic.