Search code examples
c#apicrmdynamics-crm-365

Cannot perform runtime binding on a null reference Exception with var type


I am trying to fetch data from CRM using this API. I get an error

Runtime binding on a null reference

whenever I try to get value from data.fullname. Is there any way I can fix it?

Thanks

var response = httpClient.GetAsync("contacts?$select=fullname,emailaddress1").Result;
           
if (response.IsSuccessStatusCode)
{
    var accounts = response.Content.ReadAsStringAsync().Result;

    var jRetrieveResponse = JObject.Parse(accounts);

    dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());

    try
    {
        foreach (var data in collContacts.value)
        {
            // You can change as per your need here
            if (data.fullname.Value != null)
            {
                success[i] = data.fullname.Value;
            }

            i ++;
        } 
    }
    catch (Exception)
    { 
         throw; 
    }
}
    

Solution

  • Replace

    if (data.fullname.Value != null)
    

    with this

    if  (!String.IsNullOrWhiteSpace(data.fullname.Value))
    

    OR Replace

    try
    {
        foreach (var data in collContacts.value)
        {
            // You can change as per your need here
            if (data.fullname.Value != null)
            {
                success[i] = data.fullname.Value;
            }
    
            i ++;
        } 
    }
    catch (Exception)
    { 
         throw; 
    }
    

    With

    try
    {
        foreach (var data in collContacts.value)
        {
            success[i] = data?.fullname?.Value;
            i ++;
        } 
    }
    catch (Exception)
    { 
         throw; 
    }