Codeanalysis fixes

This includes the commit from my other PR. You can ignore that one if you accept this one. 

In this one, I fixed a few Code Analysis performance rules by removing unnecessary casts. I tried to do the minimal amount of work to satisfy the rules. I think there's definitely some more refactoring worth doing later. :)

Also fixed a few design rules. Minor stuff. All tests continue to pass.