Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is casting a dynamic of type object to object throwing a null reference exception?

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); 
like image 368
bedo Avatar asked Mar 29 '12 18:03

bedo


People also ask

Which exception is caused by referencing a null object?

A NullReferenceException exception is thrown by a method that is passed null . Some methods validate the arguments that are passed to them.

How can you tell if a dynamic object is null?

In order to check a dynamic for null, you should cast it as an object. For example, dynamic post = SomeMethod(); if (post. modified == null){ //could return errors. }


1 Answers

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.

like image 137
Eric Lippert Avatar answered Sep 25 '22 18:09

Eric Lippert