Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# serialize private class member

class Person {     public string m_name;     private int m_age; // << how do I serialize the darn little rat? } 

Simple question yet it seems like a big mess when trying to answer it.
Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?
How do I serialize private class members?

Edit #1:
Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.
Anyway, here are more facts:
1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.
2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.
3.I was hoping that there's a certain attribute like:

class Person {     public string m_name;     [SerializeThat(ElementName="Age")]     private int m_age; // << how do I serialize the darn little rat? } 

OR (continue of fact #3) an attribute that goes on the class which would look like:

[Serializable(DoPrivate = true, DoProtected = true)] class Person {     public string m_name;     private int m_age; // << how do I serialize the darn little rat? } 

Now, what can I do to achieve it?

like image 239
Poni Avatar asked Nov 30 '10 14:11

Poni


People also ask

What C is used for?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


2 Answers

Going on the assumption of a typo, I'd like to redirect you to this SO article where the solution is to use a DataContractSerializer instead.

like image 69
Brad Christie Avatar answered Sep 23 '22 03:09

Brad Christie


Don't know if you can use DataContract. But with this you could write:

[DataContract] class Person {     [DataMember]     public string m_name;      [DataMember]     private int m_age; } 

The advantage of DataContract that you can serialize private fields and your class doesn't need a default constructor.

like image 23
Oliver Avatar answered Sep 26 '22 03:09

Oliver