Port a C# Class
Translate a small C# class to native C++ with explicit ownership, properties and exceptions.
Start from semantics
Record whether the C# type is value-like, who owns it, whether callbacks outlive it, and which exceptions callers depend on. Then translate the shape.
Properties become explicit accessors
class Counter final {
public:
int getValueProperty() const noexcept { return value_; }
void Increment()
{
if (value_ == INT_MAX) {
throw System::OverflowException("Counter overflow.");
}
++value_;
}
private:
int value_ = 0;
};
Choose ownership
- Use a direct member for a required value with the same lifetime.
- Use
std::unique_ptrfor exclusive heap ownership. - Use
std::shared_ptronly for real shared ownership; identify cycles. - Use references/pointers only when a longer-lived owner is already established.
Preserve observable errors
Use the specific implemented Sharp Runtime exception when callers rely on it. Do not replace every validation error with a generic std::runtime_error, and do not invent .NET behavior that the runtime does not implement.
Verify the port
- Compile warnings as errors.
- Test normal, boundary and invalid inputs.
- Test copy/move behavior if the type owns resources.
- Test callback shutdown and destruction order.