Classes with methods and properties

Category:
Defining Types
Description: Classes can contain methods of general form and properties.
Code:
type Circle2 (r : float) =    
let mutable radius = r
let area = System.Math.PI * r * r

// Read/Write property with get and set
member c.R with get() = radius and set(inp) = radius <- inp
// Read only property with get
member c.Area with get() = area

new () = Circle2(1.0)

new(text: string) =
if text = null then
raise <| new System.Exception("text")

let (successR, r) = System.Double.TryParse(text)
if not successR then
raise <| new System.Exception("text")
new Circle2(r: float)

// method with signature: member CalculateCircumference : unit -> float
member c.CalculateCircumference() = System.Math.PI * 2.0 * c.R

let ClassesSupport2() =
let c1 = Circle2(2.0)

printfn "c1.Area = %f\tc1.R = %f\n" c1.Area c1.R
c1.R <- 5.0
printfn "c1.Area = %f\tc1.R = %f\n" c1.Area c1.R

c1.CalculateCircumference()

Execution Result:
c1.Area = 12.566371	c1.R = 2.000000

c1.Area = 12.566371 c1.R = 5.000000


Last edited Sep 14, 2011 at 2:38 AM by ttliu2000, version 1

Comments

No comments yet.