C++/CLI by reference parameter is not filled

Some time ago I stumbled upon some interesting behaviour of managed references in C++/CLI. When a managed reference is passed a variable of a subtype of the declared parameter’s type, the compiler does not inform you about it, but at runtime, your variable remains empty (nullptr).

It’s obvious that this can’t work, as it would be an implicit cast to the more specific subtype. But silently failing in this case is not nice either.


#include "stdafx.h"
using namespace System;
void testEnumerable(System::Collections::Generic::IEnumerable<int>^% enumerable)
{
	enumerable = gcnew System::Collections::Generic::List<int>();
}
int main(array<System::String ^> ^args)
{
	System::Collections::Generic::List<int>^ list;
	System::Collections::Generic::IEnumerable<int>^ enumerable;
	test(list);//list remains nullptr
	test(enumerable);//enumerable is filled
	Console::ReadLine();
    return 0;
}

This entry was posted in Software. Bookmark the permalink.