Setting value of inherited trivial property in the constructor triggers Code Analysis Warning CA2214

54 Views Asked by At

I define an interface containing a trivial/simple property and an implementing class that sets the property in its constructor:

    interface class IMyInterface
    {
    public:
        property System::String^ MyName;
    };

    ref class MyImplementingClass : public IMyInterface
    {
    public:
        virtual property System::String^ MyName;

        MyImplementingClass()
        {
            MyName = "Test Name";
        }
    };

This doesn't seem too contentious, but when I run Code Analysis in Visual Studio 2019 using the default 'Microsoft Mixed (C++/CLR) Recommended Rules' ruleset it triggers warning CA2214:

warning CA2214: Microsoft.Usage : 'MyImplementingClass::MyImplementingClass(void)' contains a call chain that results in a call to a virtual method defined by the class. Review the following call stack for unintended consequences: 
warning CA2214: MyImplementingClass..ctor()
warning CA2214: MyImplementingClass.set_MyName(String):Void

So I think it's complaining because setting this property involves calling the automatically implemented method set_MyName() and since that method is virtual it is considered a violation to call it from a constructor.

Does that mean this whole pattern is invalid?

What is the correct way to set the value of an inherited property at construction time?

0

There are 0 best solutions below