I have the following function:
public static T TryGetArrayValue<T>(object[] array_, int index_)
{
... //some checking goes up here not relevant to question
dynamic boxed = array_[index_];
return (T)boxed;
}
When I call it in the following way,
object a = new object();
object v = TUtils.TryGetArrayValue<object>(new object[] { a }, 0);
(T)boxed throws a null reference exception.
Any other type I put in there other than “object”, it works perfectly fine.
Any ideas what this is, and why it’s throwing the exception?
Edit:
The reason why I use dynamic is to avoid exception when converting types, for example:
double a = 123;
int v = TUtils.TryGetArrayValue<int>(new object[] { a }, 0);
I agree with the other answerers who say that this looks like a bug. Specifically it appears to be a bug in C# runtime binding layer, though I have not investigated it thoroughly.
I apologize for the error. I’ll report it to the C# 5 testing team and we’ll see if it has already been reported and fixed in C# 5. (It reproduces in the recent beta release, so it is unlikely that it has already been reported and fixed.) If not, a fix is unlikely to make it into the final release. In that case we’ll consider it for a possible servicing release.
Thanks for bringing this to our attention. If you feel like entering a Connect issue to track it, feel free to do so and please include a link to this StackOverflow question. If you don’t, no problem; the test team will know about it either way.