Re: Saving Colors to a db

Fabian Schmied <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <[email protected]>
> 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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.