Thursday, October 21, 2010

Properties

// person.cs
using System;
class Person
{
private string myName ="N/A";
private int myAge = 0;

// Declare a Name property of type string:
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}

// Declare an Age property of type int:
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}

public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}

public static void Main()
{
Console.WriteLine("Simple Properties");

// Create a new Person object:
Person person = new Person();

// Print out the name and the age associated with the person:
Console.WriteLine("Person details - {0}", person);

// Set some values on the person object:
person.Name = "Joe";
person.Age = 99;
Console.WriteLine("Person details - {0}", person);

// Increment the Age property:
person.Age += 1;
Console.WriteLine("Person details - {0}", person);
}
}





// shapes.cs
// compile with: /target:library /reference:abstractshape.dll
public class Square : Shape
{
private int mySide;

public Square(int side, string id) : base(id)
{
mySide = side;
}

public override double Area
{
get
{
// Given the side, return the area of a square:
return mySide * mySide;
}
}
}

public class Circle : Shape
{
private int myRadius;

public Circle(int radius, string id) : base(id)
{
myRadius = radius;
}

public override double Area
{
get
{
// Given the radius, return the area of a circle:
return myRadius * myRadius * System.Math.PI;
}
}
}

public class Rectangle : Shape
{
private int myWidth;
private int myHeight;

public Rectangle(int width, int height, string id) : base(id)
{
myWidth = width;
myHeight = height;
}

public override double Area
{
get
{
// Given the width and height, return the area of a rectangle:
return myWidth * myHeight;
}
}
}





// shapetest.cs
// compile with: /reference:abstractshape.dll;shapes.dll
public class TestClass
{
public static void Main()
{
Shape[] shapes =
{
new Square(5, "Square #1"),
new Circle(3, "Circle #1"),
new Rectangle( 4, 5, "Rectangle #1")
};

System.Console.WriteLine("Shapes Collection");
foreach(Shape s in shapes)
{
System.Console.WriteLine(s);
}

}
}

No comments: