Properties for read and write (C#) : Property « Language Basics « ASP.Net






Properties for read and write (C#)

<%@ page Language="c#" runat="server" %>
<script runat="server">
public class Car
{
  private string color;
  private int gear;
  public string Color
  {
    get 
    {
      return color;
    }
    set 
    {
      color = value;
    }
  }
  public int Gear
  {
    get 
    {
      return gear;
    }
  }
  public void ChangeGear(int Direction)
  {
    if (Direction < 0)
      gear--;
    if (Direction > 0)
      gear++;
    if ( gear > 5) 
      gear = 5;
    if ( gear < -1) 
      gear = -1;
  }
}
void Page_Load()
{
  Car MyCar = new Car();
  Response.Write("<b>New object 'MyCar' created.</b>");
  Response.Write("<br/>Color: " + MyCar.Color);
  Response.Write("<br/>Gear: " + MyCar.Gear);
  MyCar.Color = "Black";
  MyCar.ChangeGear(+1);
  Response.Write("<br/><b>Properties updated.</b>");
  Response.Write("<br/>New color: " + MyCar.Color);
  Response.Write("<br/>New gear: " + MyCar.Gear);
}
</script>

           
       








Related examples in the same category

1.Throw Exception in Property setter (VB.net)
2.Define and use properties (C#)