Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error : Unable to perform runtime binding (when location/hometown/any setting is not set in facebook profile)

I am facing an error

Cannot perform runtime binding on a null reference

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference

Source Error:

Line 27: lblBirthday.Text = (myInfo.birthday == null ? string.Empty : DateTime.Parse(myInfo.birthday).ToString("dd-MMM-yy")); Line 28: lblHometown.Text = (myInfo.hometown.name == null ? string.Empty : myInfo.hometown.name); Line 29: lblLocation.Text = (myInfo.location.name == null ? string.Empty : myInfo.location.name); Line 30: pnlHello.Visible = true; Line 31: }

Here is my code :

var fb = new FacebookWebClient();
    dynamic myInfo = fb.Get("me");
    lblName.Text = myInfo.name;
    imgProfile.ImageUrl = "https://graph.facebook.com/" + myInfo.id + "/picture";
    lblBirthday.Text = (myInfo.birthday == null ? string.Empty : DateTime.Parse(myInfo.birthday).ToString("dd-MMM-yy"));
    lblHometown.Text = (myInfo.hometown.name == null ? string.Empty : myInfo.hometown.name);
    lblLocation.Text = (myInfo.location.name == null ? string.Empty : myInfo.location.name);
    pnlHello.Visible = true;
like image 611
niklodeon Avatar asked Mar 17 '11 07:03

niklodeon


1 Answers

First check for myInfo.location being null:

lblLocation.Text = myInfo.location == null ? "" : myInfo.location.name ?? "";

(And likewise for similar members.)

It's a bit of a pain, admittedly, but basically you need to account for anything that might be null, to make sure you don't try to dereference it.

like image 186
Jon Skeet Avatar answered Nov 09 '22 22:11

Jon Skeet