C #, using static keyword correctly when designing a base color class

I make a Color class and provide a standard constructor like

Color(int red, int green, int blue)

And then I want to provide an easy way to get the most common colors, like Color.Blue, Color.Red. I see two possible options:

public static readonly Color Red = new Color(255, 0, 0);

public static Color Red { get { return new Color(255, 0, 0); } }

I don’t fully understand if there is one advantage over the other and how the static keyword works. My thoughts: the first creates one instance, and then this instance remains in memory throughout the program, and every time Red is called, this instance is used. The latter only creates something on first use, but each time creates a new instance. If this is correct, I would say that if I put a lot of predefined colors, then the first will use a lot of unnecessary memory? So this is memory usage and the overhead of running an instance of an object every time I think.

Am I reasoning correctly? Any best practice tips for developing classes and using the static keyword would be great.

+3
source share
4

, , , , Color. , Color .

static, . static , , . () ; . ( ) .

, . Color (, Color , , 32- int.). Color class struct, ( 32- v-table/typeinfo, 32-), 12 . 100 , <= 1200 . .

. , , , , , , .. , :

class Heavy{
    static Heavy first;
    static Heavy second;

    public static Heavy First{
        get{
            if(first == null)
                first = new Heavy();
            return first;
        }
    }
    public static Heavy Second{
        get{
            if(second == null)
                second = new Heavy();
            return second;
        }
    }
}

. Color ? , , , ?

Color , "" , . , - - :

Color.Red.G = 255;

Color.Red .

, , :

for(int y = 0; y < bmp.Height; y++)
for(int x = 0; x < bmp.Width; x++)
    if(bmp.GetPixel(x, y) == Color.Red))
        MessageBox.Show("Found a red pixel!");

A Color . , , ( "" , ).

, Color , . , new struct, v- , , .

+7

. System.Drawing.Color, , . , , , , .

, Color . , , .

+3

, static, , , , .

, , , WPF, , . , Application.Current. , .

+1

, :

public static readonly Color RED = new Color(255, 0, 0);

Under the hood, I believe that at run time it will only be activated when it is called for the first time. But I did not check it for myself in the debugger.

And, as you say, using the static getter alternative you provide, it will fill the heap as soon as you call it. The reason is that every call will create a new object .

If you really want to use the getter alternative, but not fill the heap, then at least create a static Color class as well. Like this:

private static readonly Color RED = new Color(255, 0, 0);
    // RED is created once when it is invoked for the first time.

public static Color Red { 
    get { 
        return RED; 
            // Will return a created RED object or create one 
            // for the first time.
    } 
}
0
source

All Articles