Mohsen Sarkar
Mohsen Sarkar

Reputation: 6040

What is C# dynamic keyword equivalent in C++ CLI?

There are two project, one C++ CLI and other is C#.
The C# project has reference to C++ CLI project.

In C# I want to do this :

//method signature is somemethod(dynamic data);
somemethod("haaaii");

Now the method which is in C++ CLI project must handle this.

How to declare this method in C++ CLI ?
Also how to detect data type in C++ CLI ?

Upvotes: 6

Views: 2567

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283803

To get a method signature which C# sees as dynamic:

void TestMethod( [System::Runtime::CompilerServices::DynamicAttribute] System::Object^ arg )
{
}

But if you just want to accept all types, you can simply use System::Object^. The attribute is misleading, as it implies semantics which you will have a very hard time providing.

To discover the actual data type, use arg->GetType(). You can then use all the power of reflection and/or the DLR for discovering and invoking members at runtime.

Slightly more useful is to use the attribute on a return type, since then C# will infer dynamic semantics when the var keyword is used.

[returnvalue: System::Runtime::CompilerServices::DynamicAttribute]
System::Object^ TestReturn( void )
{
    return 1;
}

Upvotes: 6

Aniket Inge
Aniket Inge

Reputation: 25725

You might have to get dynamic with System::Dynamic::DynamicObject type

void somemethod(ref System::Dynamic::DynamicObject data) { }

Upvotes: 0

Related Questions