Like methods, properties are specified in an interface without any body. Here is the general form of a property specification:
// interface property type name { get; set; }
Of course, only get or set will be present for read-only or write-only properties, respectively.
Here is a rewrite of the ISeries interface and the ByTwos class that uses a property to obtain and set the next element in the series:
// Use a property in an interface. using System; public interface ISeries { // An interface property. int next { get; // return the next number in series set; // set next number } } // Implement ISeries. class ByTwos : ISeries { int val; public ByTwos() { val = 0; } // get or set value public int next { get { val += 2; return val; } set { val = value; } } } // Demonstrate an interface property. class SeriesDemo3 { public static void Main() { ByTwos ob = new ByTwos(); // access series through a property for(int i=0; i < 5; i++) Console.WriteLine("Next value is " + ob.next); Console.WriteLine("\nStarting at 21"); ob.next = 21; for(int i=0; i < 5; i++) Console.WriteLine("Next value is " + ob.next); } }
The output from this program is shown here:
Next value is 2 Next value is 4 Next value is 6 Next value is 8 Next value is 10 Starting at 21 Next value is 23 Next value is 25 Next value is 27 Next value is 29 Next value is 31