I’ve been playing with generics more, trying to ease the slog of C# development. The .NET framework allows you to do damn near everything, but its so freaking verbose. Almost anything I want to do with framework classes ends up taking 4-5 nearly identical lines, so I end up writing a lot of little wrapper functions to make one-liners.
The task I had at hand this time was to take a string of XML and deserialize is back into a C# object. I generated the C# object off of an .xsd file using xsd.exe (more info), so it has the spaghetti of attributes needed for the XmlSerializer.
public static T DeserializeFromXml<T>(string xml){ T result; XmlSerializer ser = new XmlSerializer(typeof(T)); using(TextReader tr = new StringReader(xml)) { result = (T) ser.Deserialize(tr); } return result; }
With that utility function, now I can just:
MyClass obj = Utils.DeserializeFromXml<MyClass>(xml);
Working with these libraries, I always end up pondering why Microsoft didn’t think to include shortcuts like this.
2 Comments