Understanding CA2214 code analysis warnings using ViewModels

If like me you didn’t understand the the rest of the message and it’s implications here is a simple explanation and answer.

When an object that implements an inherited class (e.g. a ViewModel that inherits from ViewModelBase) is constructed, the constructors in the base class or classes are executed first.

However as the base classes execute methods or events, if these implemented methods or events are overridden, by a more derived class, then the base could call these and not it’s intended base methods. This could cause some unexpected behaviour.

If you make calls to potentially override-able methods yourself (e.g. RaisePropertyChanged) , you probably intended to and know full well what the consequences are. So why the annoying message?

Well, CA2214 is warning you that this may become a problem if anyone decides to inherit from your class (e.g. your ViewModel). As this is probably not something that you want or intend in your project, you can eliminate this warning by simply sealing your class!

    public sealed class MainViewModel : ViewModelBase

This will ensure that your class cannot be inherited from. This should make the warning go away.

If you are writing your own base class or a class that is to be inherited from, then don’t call override-able methods in your constructors!

Hope that helps! hhhmmmmm

One thought on “Understanding CA2214 code analysis warnings using ViewModels

  1. It’s not enough to say, “Don’t do that.” What if you really do want initialization behavior that can be overridden in derived classes? What’s the alternative pattern?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.