Re: Saving Colors to a db
Peter Osucha <[email protected]>
| Newsgroups | gmane.comp.windows.devel.dotnet.winforms |
|---|---|
| Message-ID | <[email protected]> |
Thanks. I have used serialization for - as you say - more complex objects. I didn't realize that the Color structure was serializable. For the Colors the user can set, they can choose named or unnamed colors. However, there are many that need to be saved and there is not a lot of database interaction. I think I'll give your method a try to see how it does. Peter -----Original Message----- From: Discussion forum for developers using Windows Forms to build apps and controls [mailto:[email protected]] On Behalf Of Fabian Schmied Sent: Tuesday, July 03, 2007 10:07 AM To: [email protected] Subject: Re: [DOTNET-WINFORMS] Saving Colors to a db > What do you mean by 'using .NET serialization to store color values in a > database'? Color is serializable, so you could use .NET serialization to get a byte[] representation of a Color instance, like this: public byte[] SerializeColor (Color color) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize (stream, color); return stream.ToArray(); } } public Color DeserializeColor (byte[] bytes) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream(bytes)) { return (Color) formatter.Deserialize (stream); } } (Haven't compiled it, may contain errors.) This has the advantage that it works with arbitrary Color instances, regardless of whether they are named or not. It has disadvantages as well, though: - Serialization and deserialization will be slower than calling ToArgb/FromArgb. - It will take more space in the database than a simple integer. - You'll have a byte[] in the database and can't do any queries or indexing on the color values. If you only deal with known colors, I'd do as Ryan suggested and store the KnownColor instead. If you always have named colors, you can store the name as well. I just wanted to mention serialization for completeness, as it should work with any Color value. (Serialization is typically rather used when persisting more complex objects or object graphs in an opaque way.) Fabian