I am having a problem with the following code. It uses the Facebook c# SDK. The problem is that I am pulling and printing a list of all of my friends work history. However, when this data isn’t available I think it is causing a NullReferenceException. I have looked at a bunch of solutions online, but haven’t found one that seems to work. Any help would be appreciated.
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var accessToken = "...";
var client = new FacebookClient(accessToken);
dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });
foreach (dynamic friend in myInfo)
{
foreach (dynamic work in myInfo.work) // <---- here
{
Response.Write("Employer: " + work.employer.name + "<br/> Position:" + work.position.name + "<br/><br/>");
}
}
}
}
I have included the suggested edits but am now getting a different error:
namespace WebApplication1.Site
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var accessToken = "xxx";
var client = new FacebookClient(accessToken);
dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });
foreach (dynamic friend in myInfo)
{
**foreach (dynamic work in friend.work ?? new[] { new { employer = new { name = string.Empty }, position = new { name = string.Empty } } })**
{
Response.Write("Employer: " + myInfo.work.employer.name);
}
}
}
}
}
‘System.Collections.Generic.KeyValuePair’ does not contain a definition for ‘work’ on Line 21
You can provide an empty list to inplace of the null value to avoid the null reference exception:
You are getting the exception because foreach makes a call to .GetEnumerator() on a null value. I used a new List, but it doesn’t really matter what is put here.. as long as it isn’t null and it is enumerable.
Edit
You could provide an anonymous type that provides the properties you need: