What are static properties and how to use static properties in C#

Use static properties


/*w  w w  . j  av a2 s. c  om*/
using System;

class MyClass
{
   static int myValue;

   public static int StaticProperty
   {
      set { myValue = value; }
      get { return myValue; }
   }

}

class MainClass
{
   static void Main()
   {
      Console.WriteLine("Init Value: {0}", MyClass.StaticProperty);
      MyClass.StaticProperty = 10;
      Console.WriteLine("New Value : {0}", MyClass.StaticProperty);
   }
}

The code above generates the following result.

Example 2


class Color/*from  w  w w  . j a v a2s.c  o m*/
{
    public Color(int red, int green, int blue)
    {
        this.red = red;
        this.green = green;
        this.blue = blue;
    }
    
    int    red;
    int    green;
    int    blue;
    
    public static Color Red
    {
        get
        {
            return(new Color(255, 0, 0));
        }
    }
    public static Color Green
    {
        get
        {
            return(new Color(0, 255, 0));
        }
    }
    public static Color Blue
    {
        get
        {
            return(new Color(0, 0, 255));
        }
    }
}
class MainClass
{
    static void Main()
    {
        Color background = Color.Red;
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor