Search code examples
c#classcolorssystem.windows.media

Work with instance of class in C#


I have some troubles with a class instance and don’t understand the issue. I’m working with colored text in different classes and therefore my idea was to define this colors only one time so changing of them will be much easier.

For the definition of the colors, I specified a class called MyColors. I used System.Windows.Media and defined the RGB colors using the Color class. My idea was to specify each color as privat and add a property that generated the read access to this color, but Visual Studio sends me an error.

namespace MyProject
{
class MyColor
{
    private Color myGreen = new Color();
    myGreen = Color.FromRgb(0, 255, 0);

    #region Properties
    /// <summary>
    /// Gets my green
    /// </summary>
    /// <value>my green</value>
    static public Color MyGreen
    {
        get
        {
            return myGreen;
        }

    }
    #endregion
}
}

The sixth line "myGreen..." generates the mistake. If I change the code to the following one, it works.

namespace MyProject
{
class MyColor
{
    #region Properties
    /// <summary>
    /// Gets my green
    /// </summary>
    /// <value>my green</value>
    static public Color MyGreen
    {
        get
        {
            Color myGreen = new Color();
            myGreen = Color.FromRgb(0, 255, 0);
            return myGreen;
        }

    }
    #endregion
}
}

Can anybody explain me what I’m doing wrong. Looks like I have a wrong understanding of a class.


Solution

  • I prefer the approach you used in your first code snipped, since it doesn't require to instantiate a new Color every time that MyGreen property is accessed. But it contains a few errors:

    1. If you want the MyGreen property to be static, the underlying instance returned by its getter (get { ... }) must be declared as static too.
    2. You cannot create an instance in the class scope using multiple lines of code. That kind of code can only be executed within an inner scope like a constructor, a property or a method. Since it's unnecessary to instantiate it twice (first using the Color() constructor and then using Color.FromRgb which basically returns a new Color instance with the specified RGB values), everything can be converted into a one-liner without changing the wanted behavior.

    Below how your class should look like:

    namespace MyProject
    {
        public class MyColor
        {
            private static Color s_MyGreen = Color.FromRgb(0, 255, 0);
    
            public static Color MyGreen
            {
                get { return s_MyGreen; }
    
            }
    
            // ...
        }
    }