How to add properties to an C# interface

Syntax

Here is the general form of a property specification:


// interface property// w  w w  . ja v a2s . com
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;//from   w w  w .j av  a2  s.  co  m

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.





















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