ImmutableObjectGraph icon indicating copy to clipboard operation
ImmutableObjectGraph copied to clipboard

Add support for "InitializeFurther" partial method.

Open DamianReeves opened this issue 9 years ago • 1 comments

There are case where you may want to do some additional initialization on a class after the initialization otherwise done in the constructor. It would be helpful to add something like OnInitialized(...) (probably needs a better name) as a partial method call in the constructor. This would allow situations like the following:

public partial class Contact
{
    readonly string name;
    readonly string email;
    readonly string phoneNumber;
        readonly DateTime dateOfBirth;
}

public partial class Rolodex
{
   readonly ImmutableList<Contact> contacts;

   [UserInitialized(0)]
   readonly ImmutableDictionary<string, Contact> _contactsByName;

   [UserInitialized(1)]
   readonly ImmutableDictionary<DateTime, Contact> _contactsByDob;

   partial void InitializeFurther(ref ImmutableDictionary<string, Contact> contactsByName, 
       ref ImmutableDictionary<DateTime, Contact> contactsByDob)
   {
      contactsByName = contacts.ToImmutableDictionary(contact=>contact.Name);
      contactsByDob = contacts.ToImmutableDictionary(contact=>contact.DateOfBirth);
    }
    ...
    public Contact FindByName(string name) 
    {
       return contactsByName[name];
    }
}

Here I want to have a Rolodex which adds Contacts using the currently auto-generated AddContacts(...) method, but I also want to be able to expose methods which work against the user provided field. Right now there is no place for me to hook in and do this sort of thing.

DamianReeves avatar Sep 15 '16 03:09 DamianReeves

So to be honest, I started writing this request without remembering that readonly fields need to be initialized only in the constructor so the request ended up being more complex than I initially expected.

An alternative to the above is to allow fine grained control of what get generates per field.

DamianReeves avatar Sep 15 '16 04:09 DamianReeves