Search code examples
c#google-cloud-platformgoogle-people-api

Null reference exception on Person object in Google People API


I am trying to add a contact to my Google contacts account. This is the code:

            // Create new contact
            Google.Apis.PeopleService.v1.Data.Person person = new Google.Apis.PeopleService.v1.Data.Person();
            Name chef = new Name();
            chef.GivenName = "FirstName";
            chef.FamilyName = "FamilyName";
            EmailAddress email = new EmailAddress();
            email.Type = "work";
            email.Value = "[email protected]";
            person.EmailAddresses.Add(email);

            person.Names.Add(chef);

            ContactToCreate contactToCreate = new ContactToCreate();
            contactToCreate.ContactPerson = person;
            BatchCreateContactsRequest request = new BatchCreateContactsRequest();
            request.Contacts.Add(contactToCreate);
            request.ReadMask = "names";

            BatchCreateContactsResponse reply = service.People.BatchCreateContacts(request).Execute();

Authentication and listing the Contact Groups works fine. If I add names or email addresses to the person object I get a Null Reference Exception.

Why?


Solution

  • You can not add to the null list you need to build an object from EmailAddress

    person.EmailAddresses = new List<EmailAddress>();
    

    and

    person.Names = new List<Name>();
    

    and

    request.Contacts = new List<Contact>();