You can access non-public members via the .NET reflection API. For this reason, although public/private/internal modifiers imply some sort of security, they should really be thought of as organizational in nature, since they are easily circumvented by reflection.
DataMember attribute on private members - Whats happening under the hood
-
04-06-2022 - |
Question
[DataContract]
public class MyClass
{
[DataMember]
private string PrivateFiled;
// Other properties elided.
...
}
How is it that the PrivateFiled
is getting set by the DataContractSerializer
when serialized/deserialized, how is it able to access the private variable. What is happening under the hood? What are the concepts behind this. Also please point to some good sources on this.
Solution
OTHER TIPS
It's using reflection. You can enumerate every field in a class using it, even the private ones, and you can also set them or get their values.
The serializer looks at the attributes that are set on the class, its fields and properties, and if it finds a particular attribute, here DataMember
, it knows that it has to serialize/deserialize it.
here about attributes: http://msdn.microsoft.com/en-us/library/z919e8tw.aspx
and here about setting private fields: Is it possible to set private property via reflection?