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.
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:
MyGreen
property to be static
, the underlying instance returned by its getter (get { ... }
) must be declared as static
too.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; }
}
// ...
}
}