I have a C++/CLI wrapper class to interop between C# and native C++. I’m getting a strange error related with System.Nullable. I understand that, for basic types, System.Nullable<T> is equivalent to T?. So I do this:
C#:
public int? RoboticsArmRotation {
get { return mRobotics.ArmRotation; }
}
C++/CLI, interface:
virtual property System::Nullable<int>^ ArmRotation{ System::Nullable<int>^ get() = 0; }
C++/CLI, concrete class:
virtual property System::Nullable<int>^ ArmRotation {
System::Nullable<int>^ get() {
boost::optional<int> value = m_pNativeInstance->getArmRotation();
return value.is_initialized()? gcnew System::Nullable<int>(value.get()) : gcnew System::Nullable<int>();
}
}
But I get the title’s compile error. Casting to int? solves it, but what bugs me is that it’s saying System.ValueType when I defined my nullable as a reference. Can I leave the cast and move on, or am I doing something wrong?
You’re using
Nullable<int>^which is a reference. Since references with a value type aren’t directly supported by the runtime, the actual type at the IL level isValueTypethat’s tagged withNullable<int>^in a way that C++/CLI supports, but C# doesn’t. For C# it’s just typed asSystem.ValueType.This makes even less sense for nullables than for normal value types, since nullables get boxed as their underlying type.
I’d recommend not declaring the field as a reference in C++ either, but to use a simple
Nullable<int>.