SlideShare a Scribd company logo
Chapter 8
Class-Constructor
of Class
Agenda
• Introduction
• Constructors
• let and do Bindings
• Self Identifiers
• Generic Type Parameters
• Specifying Inheritance
• Members Section
• When to Use Classes, Unions, Records, and
Structures
What is Class?
• Classes are types that represent objects that can have
properties, methods, and events.
• Before an object is created, its properties and functions
should be defined.
• We define properties and methods of an object in a class.
How to define Class?
• There are two different syntaxes for defining a class:
implicit An explicit
Syntax to
Defining Class
Implicit Class Construction
type TypeName optional-type-arguments arguments [ as ident ] =
[ inherit type { as base } ]
[ let-binding | let-rec bindings ] *
[ do-statement ] *
[ abstract-binding | member-binding | interface-implementation ] *
//specify the base class for a class.
declare fields or function values local
to the class.
includes code to be executed upon object
construction.
Example
• Defines a class called Account, which has three properties
and two methodsAccountClass
Properties
Number
Name
Account
Methods
Deposit
Withdraw
Example
type Account(number : int, name : string) = class
let mutable amount = 0
member x.Number = number
member x.Name = name
member x.Amount = amount
member x.Deposit(value) =
amount <- amount + value
member x.Withdraw(value) =
amount <- amount - value
end
Properties / Data
members
Methods
Example
• The underlined code is called the class constructor.
• A constructor is a function used to initialize the
fields in an object.
• Here, constructor defines two values, number and
name which can be accessed anywhere in our class.
Instance Creation
• new keyword is used to create
let amar = new Account(123456, “Amar’s Saving")
let printAccount (x : Account) =
printfn "x.Number: %i, x.Name: %s, x.Amount:
%d" x.Number x.Name x.Amount
printAccount Amar
As whole
type Account(number : int, holder : string) = class
let mutable amount = 0m
member x.Number = number
member x.Holder = holder
member x.Amount = amount
member x.Deposit(value) = amount <- amount + value
member x.Withdraw(value) = amount <- amount - value
end
let Amar = new Account(123456, "Amar’s Saving")
let printAccount (x : Account) =
printfn "x.Number: %i, x.Holder: %s, x.Amount: %d" x.Number x.Holder
x.Amount;;
printAccount Amar
OUTPUT
x.Number: 123456, x.Name:
Amar’s Saving, x.Amount: 0
Deposit & Withdraw
Amar.Deposit(10000)
printAccount Amar
Amar.Withdraw(5000)
printAccount Amar
Let & Do Bindings
• Form the body of the primary class constructor, and
therefore they run whenever a class instance is
created
• If a let binding is a function, then it is compiled into a
member
• if the let binding is a value that is not used in any
function or member, then it is compiled into a variable
that is local to the constructor.
• if the let binding is a value that is used in any function
or member, it is compiled into a field of the class.
Let & Do Bindings
• The do bindings execute initialization code for every
instance.
• let bindings and do bindings always execute regardless
of which constructor is called.
• Fields that are created by let bindings can be accessed
throughout the methods and properties of the class
but not from static method;
Let & Do Bindings
type Greetings(name) as gr =
let data = name
do
gr.PrintMessage()
member this.PrintMessage() =
printf "Hello %sn" data
let g1 = new Greetings("Good Morning!")
Explicit Class Construct :Syntax
type TypeName =
[ inherit type ]
[ val-definitions ]
[ new ( optional-type-arguments arguments ) [ as ident ] =
{ field-initialization }
[ then constructor-statements ]
] *
[ abstract-binding | member-binding | interface-implementation ] *
Creates a line class along with a
constructor that calculates the length of
the line while an object of the class is
created
type Line = class
val X1 : float
val Y1 : float
val X2 : float
val Y2 : float
new (a, b, c, d) =
{ X1 = a; Y1 = b; X2 = c; Y2 =d}
then
printfn " Creating Line: {(%g, %g), (%g, %g)}nLength: %g"
this.X1 this.Y1 this.X2 this.Y2 this.Length
member m.Length =
let sqr m = m * m
sqrt(sqr(m.X1 - m.X2) + sqr(m.Y1 - m.Y2) )
End
let L1= new Line(1.0, 1.0, 4.0, 5.0)
val defines a field in our object.
Unlike other object-oriented languages, F# does not implicitly
initialize fields in a class to any value. Instead, F# requires
programmers to define a constructor and explicitly initialize
each field
a then block is used to Perform
some post-constructor processing
using
What is Differences Between
Implicit and Explicit Syntaxes
???
Major difference between the two syntaxes
is related to the constructor
explicit syntax
forces a
programmer to
provide explicit
constructor(s)
implicit syntax
fuses
the primary
constructor with
the class body.
Few more differences………
implicit syntax explicit syntax
• Allow programmers to declare
let and do bindings.
• Does not allow programmers to
declare let and do bindings.
• The primary constructor
parameters are visible
throughout the whole class
body
• val defines a field
• When you declare additional
constructors, they must call the
primary constructor
• all constructors are declared with
new() and there is no primary
constructor that needs to be
referenced from others.
Class with primary (implicit) constructor Class with only explicit constructors
// The class body acts as a constructor
type Car1(make : string, model :
string)=class
// x.Make and x.Model are property getters
member x.Make = make
member x.Model = model
// This is an extra constructor.
// It calls the primary constructor
new () = Car1("default make", "default
model")
end
type Car2 = class
// In this case, we need to declare // all fields
and their types explicitly
val private make : string
val private model : string
// Notice how field access differs
// from parameter access
member x.Make = x.make
member x.Model = x.model
// Two constructors
new (make : string, model : string) = { make =
make model = model }
new () = { make = "default make" model =
"default model" }
end
Example :
Normal functions, methods can
have parameters, call other
methods, and be parameterless
method
type MethodExample() =
// standalone method
member this.AddOne x =
x + 1
// calls another method
member this.AddTwo x =
this.AddOne x |> this.AddOne
// parameterless method
member this.Pi() =
3.14159
let me = new MethodExample()
printfn "%i" <| me.AddOne 42
printfn "%i" <| me.AddTwo 42
printfn "%f" <| me.Pi()
Example :
Tuple form vs. curried form
Unlike normal functions, methods with more than one
parameter can be defined in two different ways:
1. The curried form, where parameters are separated
with spaces, and partial application is supported.
2. The tuple form, where all the parameters as passed in
at the same time, comma-separated, in a single tuple.
type TupleAndCurriedMethodExample() =
// curried form
member this.CurriedAdd x y =
x + y
// tuple form
member this.TupleAdd(x,y) =
x + y
let tc = new TupleAndCurriedMethodExample()
printfn "%i" <| tc.CurriedAdd 1 2
printfn "%i" <| tc.TupleAdd(1,2)
// use partial application
let addOne = tc.CurriedAdd 1
printfn "%i" <| addOne 99
https://fsharpforfunandprofit.com/posts/classes/

More Related Content

What's hot

Classes1
Classes1Classes1
Classes1
phanleson
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
Vineeta Garg
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Op ps
Op psOp ps
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
M Vishnuvardhan Reddy
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
Shivam Singh
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
PRN USM
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
Chinedu Ekwunife
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
Mahmoud Alfarra
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
Templates
TemplatesTemplates
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
Andrew Ferlitsch
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
DrRajeshreeKhande
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Java Methods
Java MethodsJava Methods
Java Methods
Rosmina Joy Cabauatan
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
Arduino Aficionado
 

What's hot (20)

Classes1
Classes1Classes1
Classes1
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Op ps
Op psOp ps
Op ps
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Arrays
ArraysArrays
Arrays
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Templates
TemplatesTemplates
Templates
 
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 

Similar to .NET F# Class constructor

Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Object and class
Object and classObject and class
Object and class
mohit tripathi
 
02.adt
02.adt02.adt
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
Object oriented design
Object oriented designObject oriented design
Object oriented design
lykado0dles
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
KevinNicolaNatanael
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
Palak Sanghani
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
JITTAYASHWANTHREDDY
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
 
Java class
Java classJava class
Java class
Arati Gadgil
 
Class and object
Class and objectClass and object
Class and object
prabhat kumar
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro C# Book
 
The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189
Mahmoud Samir Fayed
 

Similar to .NET F# Class constructor (20)

Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Object and class
Object and classObject and class
Object and class
 
02.adt
02.adt02.adt
02.adt
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Object oriented design
Object oriented designObject oriented design
Object oriented design
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
Java class
Java classJava class
Java class
 
Class and object
Class and objectClass and object
Class and object
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189
 

More from DrRajeshreeKhande

.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading
DrRajeshreeKhande
 
Exception Handling in .NET F#
Exception Handling in .NET F#Exception Handling in .NET F#
Exception Handling in .NET F#
DrRajeshreeKhande
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interface
DrRajeshreeKhande
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
DrRajeshreeKhande
 
F# Console class
F# Console classF# Console class
F# Console class
DrRajeshreeKhande
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
DrRajeshreeKhande
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
DrRajeshreeKhande
 
F# array searching
F#  array searchingF#  array searching
F# array searching
DrRajeshreeKhande
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
DrRajeshreeKhande
 
.Net (F # ) Records, lists
.Net (F # ) Records, lists.Net (F # ) Records, lists
.Net (F # ) Records, lists
DrRajeshreeKhande
 
MS Office for Beginners
MS Office for BeginnersMS Office for Beginners
MS Office for Beginners
DrRajeshreeKhande
 
Java Multi-threading programming
Java Multi-threading programmingJava Multi-threading programming
Java Multi-threading programming
DrRajeshreeKhande
 
Java String class
Java String classJava String class
Java String class
DrRajeshreeKhande
 
JAVA AWT components
JAVA AWT componentsJAVA AWT components
JAVA AWT components
DrRajeshreeKhande
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
DrRajeshreeKhande
 
Dr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to java
DrRajeshreeKhande
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
DrRajeshreeKhande
 
Dr. Rajeshree Khande : Java Basics
Dr. Rajeshree Khande  : Java BasicsDr. Rajeshree Khande  : Java Basics
Dr. Rajeshree Khande : Java Basics
DrRajeshreeKhande
 

More from DrRajeshreeKhande (19)

.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading
 
Exception Handling in .NET F#
Exception Handling in .NET F#Exception Handling in .NET F#
Exception Handling in .NET F#
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interface
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
 
F# Console class
F# Console classF# Console class
F# Console class
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
F# array searching
F#  array searchingF#  array searching
F# array searching
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
 
.Net (F # ) Records, lists
.Net (F # ) Records, lists.Net (F # ) Records, lists
.Net (F # ) Records, lists
 
MS Office for Beginners
MS Office for BeginnersMS Office for Beginners
MS Office for Beginners
 
Java Multi-threading programming
Java Multi-threading programmingJava Multi-threading programming
Java Multi-threading programming
 
Java String class
Java String classJava String class
Java String class
 
JAVA AWT components
JAVA AWT componentsJAVA AWT components
JAVA AWT components
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
 
Dr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to java
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
 
Dr. Rajeshree Khande : Java Basics
Dr. Rajeshree Khande  : Java BasicsDr. Rajeshree Khande  : Java Basics
Dr. Rajeshree Khande : Java Basics
 

Recently uploaded

Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 

Recently uploaded (20)

Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 

.NET F# Class constructor

  • 2. Agenda • Introduction • Constructors • let and do Bindings • Self Identifiers • Generic Type Parameters • Specifying Inheritance • Members Section • When to Use Classes, Unions, Records, and Structures
  • 3. What is Class? • Classes are types that represent objects that can have properties, methods, and events. • Before an object is created, its properties and functions should be defined. • We define properties and methods of an object in a class.
  • 4. How to define Class? • There are two different syntaxes for defining a class: implicit An explicit Syntax to Defining Class
  • 5. Implicit Class Construction type TypeName optional-type-arguments arguments [ as ident ] = [ inherit type { as base } ] [ let-binding | let-rec bindings ] * [ do-statement ] * [ abstract-binding | member-binding | interface-implementation ] * //specify the base class for a class. declare fields or function values local to the class. includes code to be executed upon object construction.
  • 6. Example • Defines a class called Account, which has three properties and two methodsAccountClass Properties Number Name Account Methods Deposit Withdraw
  • 7. Example type Account(number : int, name : string) = class let mutable amount = 0 member x.Number = number member x.Name = name member x.Amount = amount member x.Deposit(value) = amount <- amount + value member x.Withdraw(value) = amount <- amount - value end Properties / Data members Methods
  • 8. Example • The underlined code is called the class constructor. • A constructor is a function used to initialize the fields in an object. • Here, constructor defines two values, number and name which can be accessed anywhere in our class.
  • 9. Instance Creation • new keyword is used to create let amar = new Account(123456, “Amar’s Saving") let printAccount (x : Account) = printfn "x.Number: %i, x.Name: %s, x.Amount: %d" x.Number x.Name x.Amount printAccount Amar
  • 10. As whole type Account(number : int, holder : string) = class let mutable amount = 0m member x.Number = number member x.Holder = holder member x.Amount = amount member x.Deposit(value) = amount <- amount + value member x.Withdraw(value) = amount <- amount - value end let Amar = new Account(123456, "Amar’s Saving") let printAccount (x : Account) = printfn "x.Number: %i, x.Holder: %s, x.Amount: %d" x.Number x.Holder x.Amount;; printAccount Amar OUTPUT x.Number: 123456, x.Name: Amar’s Saving, x.Amount: 0
  • 11. Deposit & Withdraw Amar.Deposit(10000) printAccount Amar Amar.Withdraw(5000) printAccount Amar
  • 12. Let & Do Bindings • Form the body of the primary class constructor, and therefore they run whenever a class instance is created • If a let binding is a function, then it is compiled into a member • if the let binding is a value that is not used in any function or member, then it is compiled into a variable that is local to the constructor. • if the let binding is a value that is used in any function or member, it is compiled into a field of the class.
  • 13. Let & Do Bindings • The do bindings execute initialization code for every instance. • let bindings and do bindings always execute regardless of which constructor is called. • Fields that are created by let bindings can be accessed throughout the methods and properties of the class but not from static method;
  • 14. Let & Do Bindings type Greetings(name) as gr = let data = name do gr.PrintMessage() member this.PrintMessage() = printf "Hello %sn" data let g1 = new Greetings("Good Morning!")
  • 15. Explicit Class Construct :Syntax type TypeName = [ inherit type ] [ val-definitions ] [ new ( optional-type-arguments arguments ) [ as ident ] = { field-initialization } [ then constructor-statements ] ] * [ abstract-binding | member-binding | interface-implementation ] *
  • 16. Creates a line class along with a constructor that calculates the length of the line while an object of the class is created
  • 17. type Line = class val X1 : float val Y1 : float val X2 : float val Y2 : float new (a, b, c, d) = { X1 = a; Y1 = b; X2 = c; Y2 =d} then printfn " Creating Line: {(%g, %g), (%g, %g)}nLength: %g" this.X1 this.Y1 this.X2 this.Y2 this.Length member m.Length = let sqr m = m * m sqrt(sqr(m.X1 - m.X2) + sqr(m.Y1 - m.Y2) ) End let L1= new Line(1.0, 1.0, 4.0, 5.0) val defines a field in our object. Unlike other object-oriented languages, F# does not implicitly initialize fields in a class to any value. Instead, F# requires programmers to define a constructor and explicitly initialize each field a then block is used to Perform some post-constructor processing using
  • 18. What is Differences Between Implicit and Explicit Syntaxes ???
  • 19. Major difference between the two syntaxes is related to the constructor explicit syntax forces a programmer to provide explicit constructor(s) implicit syntax fuses the primary constructor with the class body.
  • 20. Few more differences……… implicit syntax explicit syntax • Allow programmers to declare let and do bindings. • Does not allow programmers to declare let and do bindings. • The primary constructor parameters are visible throughout the whole class body • val defines a field • When you declare additional constructors, they must call the primary constructor • all constructors are declared with new() and there is no primary constructor that needs to be referenced from others.
  • 21. Class with primary (implicit) constructor Class with only explicit constructors // The class body acts as a constructor type Car1(make : string, model : string)=class // x.Make and x.Model are property getters member x.Make = make member x.Model = model // This is an extra constructor. // It calls the primary constructor new () = Car1("default make", "default model") end type Car2 = class // In this case, we need to declare // all fields and their types explicitly val private make : string val private model : string // Notice how field access differs // from parameter access member x.Make = x.make member x.Model = x.model // Two constructors new (make : string, model : string) = { make = make model = model } new () = { make = "default make" model = "default model" } end
  • 22. Example : Normal functions, methods can have parameters, call other methods, and be parameterless method
  • 23. type MethodExample() = // standalone method member this.AddOne x = x + 1 // calls another method member this.AddTwo x = this.AddOne x |> this.AddOne // parameterless method member this.Pi() = 3.14159 let me = new MethodExample() printfn "%i" <| me.AddOne 42 printfn "%i" <| me.AddTwo 42 printfn "%f" <| me.Pi()
  • 24. Example : Tuple form vs. curried form Unlike normal functions, methods with more than one parameter can be defined in two different ways: 1. The curried form, where parameters are separated with spaces, and partial application is supported. 2. The tuple form, where all the parameters as passed in at the same time, comma-separated, in a single tuple.
  • 25. type TupleAndCurriedMethodExample() = // curried form member this.CurriedAdd x y = x + y // tuple form member this.TupleAdd(x,y) = x + y let tc = new TupleAndCurriedMethodExample() printfn "%i" <| tc.CurriedAdd 1 2 printfn "%i" <| tc.TupleAdd(1,2) // use partial application let addOne = tc.CurriedAdd 1 printfn "%i" <| addOne 99