Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use FormatterServices.GetUnitializedObject instead of constructor with default values. #207

Closed
Wazner opened this issue Feb 28, 2016 · 2 comments

Comments

@Wazner
Copy link
Contributor

Wazner commented Feb 28, 2016

Currently when Jil determines the field addresses for optimal order, it will try to create an instance of the type using the constructor with the least amount of arguments. (See: Utils.cs line 467)

This will fail when the constructor does anything with the objects, for example:

class Test {
    private readonly int _a;

    public Test(OtherType b) {
        _a = b.A;
    }

    public int A {
        get { return _a; }
    }
}

I suggest using FormatterServices.GetUninitializedObject instead, this will create an instance of the object without calling any constructor, all fields will be initialized with its default value. The only downside to this is that the call will take about 11% longer than just using Activator.CreateInstance. A possible hybrid is to use Activator.CreateInstance when there is a default constructor, otherwise use FormatterServices.GetUninitializedObject.

This change allows objects that will never be deserialized anyway, be serialized without adding an empty constructor just for serialization.

I'm posting this as an issue so there is a place for discussion, I'm happy to post a pull request when you think this is an useful change @kevin-montrose.

@kevin-montrose
Copy link
Owner

Sounds like a good idea to me, I'd consider a pull request.

@Timovzl
Copy link

Timovzl commented Mar 19, 2018

I would definitely opt for always using GetUninitializedObject. I've had issues with the default constructor "doing things" and then being inadvertently hit by deserialization (and, shockingly, even by serialization).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants