Constructing Classes

Category:
Defining Types
Description: Classes are custom types containing data (known as 'fields'), methods, and properties ( methods without parameters). Classes are reference types and are stored on the Heap. Classes must be constructed and instantiated to use. Unlike C#, no default constructor is provided, one must be defined.
Code:
type Circle (r: float) =
let area = System.Math.PI * r * r
do printfn "Initialized a circle with radius %f\n" r

member this.R = r
member this.Area = area

new () = new Circle(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 Circle(r: float)


let ClassesSupport() =
let c1 = new Circle()
let area1 = c1.Area

let c2 = new Circle(6.0)
let area2 = c2.Area

let c3 = new Circle("3")
let area3 = c3.Area

printfn "area1 = %f\n" area1
printfn "area2 = %f\n" area2
printfn "area3 = %f\n" area3

Execution Result:
Initialized a circle with radius 1.000000

Initialized a circle with radius 6.000000

Initialized a circle with radius 3.000000

area1 = 3.141593

area2 = 113.097336

area3 = 28.274334


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

Comments

No comments yet.