Reputation: 333
I'm working on a piece of legacy code & I'm trying to update some of the interface. I'm not proficient in C++/CLI and the documentation for C++/CLI is sparse at best. I do my best to convert C# documentation to C++/CLI but it doesn't always work.
I want to convert a System::Object to a ContextMenuStrip.
A sample code is:
System::Void Form1::unzoomToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)
{
System::Windows::Forms::ContextMenuStrip ^menu = sender;
//a value of type "System::Object ^" cannot be used to initialize and entity of type "System::Windows::Forms::ContextMenuStrip ^"
//Other code here
}
How is this done in C++/CLI?
Upvotes: 0
Views: 278
Reputation: 154
From the link posted by Hans Passant:
A downcast is a cast from a base class to a class that's derived from the base class. A downcast is safe only if the object that's addressed at runtime is actually addressing a derived class object. Unlike static_cast, safe_cast performs a dynamic check and throws InvalidCastException if the conversion fails.
So you should use:
Windows::Forms::ContextMenuStrip ^menu = safe_cast<Windows::Forms::ContextMenuStrip^>(sender);
Upvotes: 2