C#. Object -> Dictionary -> Object

I have the fallowing situation. I have an object. I need to make a Dictionary, which contains all the properties (and it's values) of the object. Then send this Dictionary over the network. In client side the Dictionary will be received and then all the data from Dictionary will be put to an object. It's also possible to serialize an object and then send it over the network (without making a Dictionary object) but we decided that it's better to make a Dictionary. So, the code:
class PackageMaker { #region Methods /// <summary> /// Scans object and adds entries to a dictionary /// </summary> /// <param name="serializableObject">Object needs to be scanned</param> /// <returns>Dictionary with properties and their values</returns> public Dictionary<string, string> AddToPackage(Object serializableObject) { if (serializableObject == null) throw new ArgumentNullException("serializableObject is not initialized!"); Dictionary<string, string> package = new Dictionary<string, string>(); foreach (PropertyInfo packetInfo in serializableObject.GetType().GetProperties()) { package.Add(packetInfo.Name, packetInfo.GetValue(serializableObject, null).ToString()); } return package; } /// <summary> /// Extracts data from dictionary and sets the data to a object /// </summary> /// <param name="packet">Dictionary with properties and their values</param> /// <param name="deserializedObject">Object which set values</param> public void MakeObjectFromPackage(Dictionary<string, string> packet, Object deserializedObject) { if (deserializedObject == null) throw new ArgumentNullException("serializableObject is not initialized!"); foreach (KeyValuePair<string, string> entry in packet) { if (deserializedObject.GetType().GetProperty(entry.Key) != null) { deserializedObject.GetType().GetProperty(entry.Key).SetValue(deserializedObject, entry.Value, null); } } } #endregion }
It looks like it's working :)

Komentarai

"It’s also possible to serialize an object and then send it over the network (without making a Dictionary object) but we decided that it’s better to make a Dictionary."

And why the fuck is that? You just basically reimplemented serialization...

Yeah, that's correct. :)
We were discussing this problem. The main point is, that there might be lots of classes, so we thought it would be better to send one big object then lots of small ones.

Interesting code.

Komentuoti