Question

In reference to this question's answer:

Note that the constructor does not have to be public. Most serializers do very well with private parameterless constructors or none at all, if they implemented to use uninitialized object construction, that is available from Reflection in at least the .Net full profile.

If I had this generic class:

public class FooClass
{
    int X { get; set; }
    int Y { get; set; }

    private FooClass() { }
}

How is it that a serializer has access to a private constructor? I always thought of them as some sort of external library and I'm curious as to why/how they can call a private constructor whereas it's impossible for me to to so manually outside of the class.

I understand why you need a private construction, but I'm curious as to how it works.

Was it helpful?

Solution

Why

Because you may want to initialize your instances when marshalling/unmarshalling an object (across an appdomain, across a network etc) in a different way. In other words, you may have different business logic for creating a blank state instance and for creating a clone from a pre-existing state.

How

You can use reflection with Activator.CreateInstance to initialize an object using a private/protected/etc constructor. One of its overloads takes a boolean specifying whether the constructor is non-public.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top