Jonathan Wood
Jonathan Wood

Reputation: 67315

How Does System.Drawing.Color Struct Initialize Colors?

I need to create a type that contains a few methods and a long list of constants.

After a little research, I think I'd like to take the same approach taken by the System.Drawing.Color struct. However, looking at the source for this structure (generated from meta data) gives me something like the following.

public byte A { get; }
public static Color AliceBlue { get; }
public static Color AntiqueWhite { get; }
public static Color Aqua { get; }
public static Color Aquamarine { get; }
public static Color Azure { get; }
public byte B { get; }
// ...

Can anyone explain to me how the static Color values (which are the same type as the containing struct) ever get initialized? I must be missing something.

Upvotes: 4

Views: 3236

Answers (2)

Jason Moore
Jason Moore

Reputation: 3374

Using the .NET Reflector (derived code below), we can see that a new color struct is created each time the static Color property (ex: AliceBlue) is called. Microsoft probably implemented it this way to ensure immutable values for this property.

public static Color AliceBlue
{
    get
    {
        return new Color(KnownColor.AliceBlue);
    }
}

An internal constructor is called and passes an enum value (KnownColor.AliceBlue) to the contstructor. The Color structure stores this enum and sets a flag/state that it is a known color.

internal Color(KnownColor knownColor)
{
    this.value = 0L;
    this.state = StateKnownColorValid;
    this.name = null;
    this.knownColor = (short) knownColor;
}

Further, from analyzing the .NET Reflector code, when you try to get a value out of the Color structure (such as the R property), the property does a search on a lookup table (i.e. private static array) using the knownColor enum and returns an Int64 representing all of the color information. From there it does some bit manipulation (bitwise AND, bit shifts, etc.) to come up with the byte representing the R (or G or B, etc.) value.

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160982

If you look at the Color class with Reflector you will see:

public static Color AliceBlue
{
    get
    {
        return new Color(KnownColor.AliceBlue);
    }
}

That confirms that a new Color object is returned every time.

Upvotes: 5

Related Questions