arie
arie

Reputation: 832

Sending null from C++/CLI to managed C#

I have a C++/CLI wrapper to be able to call C# code. In the C# code I have a method which accepts a nullable enum as parameter, but I can't figure out how I can call this method with a null parameter from my wrapper.

C# method:

public int DoSomething(MyEnum? option)
{
    if (option != null)
        //Do something
    else
        //Do something else 
}

The C++ function calling DoSomething():

int MyMethod(int option)
{
    int myVal;
    if (option > -1)
    {
        myVal = component->DoSomething((CSharpNameSpace::MyEnum)option); //This works
    }
    else
    {
        myVal = component->DoSomething(??); //I want to send null here
    }
}

I tried several things but nothing has worked so far:

I don't have control of the C# code, so I can't change the enum to have a none value or anything like that.

Upvotes: 0

Views: 844

Answers (1)

Hans Passant
Hans Passant

Reputation: 942040

Nullable types don't get any syntax love in C++/CLI, very unlike C#. The basic obstacle you run into is that there is no implicit conversion from nullptr to Nullable. A simple way is to rely on the default constructor:

int MyMethod(int option)
{
    Nullable<ClassLibrary1::MyEnum> enu;
    if (option > -1) enu = safe_cast<ClassLibrary1::MyEnum>(option);
    return component->DoSomething(enu);
}

Upvotes: 4

Related Questions