A simple property example

image_pdfimage_print

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// A simple property example. 
 
using System; 
 
class SimpProp {  
  int prop; // field being managed by myprop 
 
  public SimpProp() { prop = 0; } 
 
  /* This is the property that supports access to 
     the private instance variable prop.  It 
     allows only positive values. */ 
  public int myprop { 
    get { 
      return prop; 
    } 
    set { 
      if(value >= 0) prop = value; 
    }  
  } 
}  
  
// Demonstrate a property. 
public class PropertyDemo {  
  public static void Main() {  
    SimpProp ob = new SimpProp(); 
 
    Console.WriteLine("Original value of ob.myprop: " + ob.myprop); 
 
    ob.myprop = 100; // assign value 
    Console.WriteLine("Value of ob.myprop: " + ob.myprop); 
 
    // Can't assign negative value to prop 
    Console.WriteLine("Attempting to -10 assign to ob.myprop"); 
    ob.myprop = -10; 
    Console.WriteLine("Value of ob.myprop: " + ob.myprop); 
  } 
}