What does it mean using parentheses in this code
I have a piece of code here, but I don't understand the use of "new (code)" in it.
type Product (code:string, price:float) =
let isFree = price=0.0
new (code) = Product(code,0.0)
member this.Code = code
member this.IsFree = isFree
In particular, why is it necessary to enclose the variable "code" within parentheses.
source to share
This is a constructor. From MSDN: Classes (F #) (see Constructors section):
You can add additional constructors using the new add member keyword as shown below:
new (argument-list) = constructor-body
In your example, the type Product
has one default constructor that accepts code
and price
, and one additional constructor that only accepts code
and applies the default constructor with 0.0
for price
. In this case, the parentheses around code
are not strictly required and the code will compile without it, although it will be required if you want the constructor to take null parameters or multiple parameters.
The C # equivalent would be something like this:
public class Product
{
private string code;
private bool isFree;
public Product(string code, double price) {
this.code = code;
this.isFree = price == 0.0;
}
public Product(string code) : this(code, 0.0) { }
public string Code { get { return this.code; } }
public float IsFree { get { return this.isFree; } }
}
source to share