C# Interface Properties

In this chapter you will learn:

  1. How to add properties to an interface
  2. Example for Interface Properties

Syntax

Here is the general form of a property specification:


// interface property/*from w w  w.j  ava  2  s .  c o  m*/
type name {
    get;
    set;
}

Example

The following code create an interface with an empty property getter setting. The implementation provides logic to the getter.


using System;// www  .  j  a  v a  2 s . com

interface IVolumeControl
{
    int Current
    {
        get;
    }
}

interface ISpeedControl
{
    int Current
    {
        get;
    }
}

public class Radio : IVolumeControl, ISpeedControl
{
    int IVolumeControl.Current
    {
        get
        {
            return 1;
        }
    }
    int ISpeedControl.Current
    {
        get
        {
            return 2;
        }
    }
}

class Class1
{ 
    [STAThread]
    static void Main(string[] args)
    {
       ISpeedControl radioDial = (ISpeedControl) new Radio();
       Console.WriteLine( "Current Speed = {0}", radioDial.Current );
    }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is interface and struct boxing
Home »
  C# Tutorial »
    C# Types »
      C# Interface
C# Interfaces
C# interface implementation
C# Explicit interface
C# Interface inheritance
C# Indexer in an interface
C# Interface Properties
C# struct and interface
C# virtual interface