C# Static Properties

In this chapter you will learn:

  1. What are static properties and how to use static properties
  2. Create new instance in static Properties

Use static properties


//w  w w. j av  a2  s . c  o  m
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/* ww  w .  j a  v  a2 s  .co 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.

Next chapter...

What you will learn in the next chapter:

  1. What is abstract properties
  2. Example for C# Abstract Properties
Home »
  C# Tutorial »
    C# Types »
      C# Properties
C# Properties
C# property accessor modifiers
C# read or write only property
C# Automatic properties
C# Static Properties
C# Abstract Properties