Page 1 of 1

Private Fields in Abstract Base Class

Posted: Tue Aug 13, 2019 2:17 am
by Exonto
Hello,

I am running into a pretty odd issue where a private field in an abstract base class is failing to be serialized despite having the [SerializeField] attribute. But when I change the field from private to public or protected, then it gets serialized correctly. This is made even more strange since all the other private fields have no problem being serialized. I have tested saving the same field in another class as private and it worked fine as well (needless to say this took forever to debug). The field in question is a class which contains a couple of generic member variables which are being serialized, in case that matters. My work around for now is to set the field as protected.

Have you run into this issue in the past? It seems very niche. Thank you.

Re: Private Fields in Abstract Base Class

Posted: Tue Aug 13, 2019 9:11 pm
by Joel
Hi there,

This is expected behaviour, and is defined by .NET's reflection libraries. Making the field private in the abstract class means that it is no longer in the scope of the derived class, and the abstract class is not treated in the same way as a concrete parent class by reflection, so its fields are not gathered.

As you've suggested, making the abstract field protected or public will bring it back into the scope.

I've added a feature request to add an edge case for this if anyone is interested: https://moodkie.com/forum/viewtopic.php?f=14&t=1717

All the best,
Joel

Re: Private Fields in Abstract Base Class

Posted: Wed Aug 14, 2019 2:09 am
by Exonto
Interesting, okay. It seems this is not a hard and fast rule though since I can serialize private primitives and other classes sometimes. Thank you.

Re: Private Fields in Abstract Base Class

Posted: Wed Aug 14, 2019 6:43 am
by Joel
Hi there,

This is a hard rule set by .NETs reflection classes. Could you give me an example of where you've been able to serialise a private field of an abstract class?

All the best,
Joel