Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating types: when using new?

I have a type mapping a class in f# as follows:

type MyClass =
   val myval: integer
   new () = {
      myval = 0;
   }
   member self.MyVal with
      get () = self.myval

Well, I want to create an instance of this class. I can do so:

let myinstance = MyClass ()

or

let myinstance = new MyClass ()

What's the difference? Can I do both?

like image 982
Andry Avatar asked Dec 17 '22 17:12

Andry


1 Answers

Technically, one difference is that you should use new when creating IDisposable objects as nyinyithann already explained. Another difference is that you can omit type arguments when creating generic type:

// Works and creates Dictionary<int, string>
let r1 = System.Collections.Generic.Dictionary 10 
r1.Add(10, "A")

// You get a compiler error when you write this:
let r2 = new System.Collections.Generic.Dictionary 10 
r2.Add(10, "A")

Aside from these two things, there is no technical difference (and there is certainly no difference in the generated IL when you write or omit new).

Which one should you use when? This is a matter of style. This is not covered by any F# coding standards, so it depends on your preference. Now that I'm thinking about it, I probably don't have very consistent style myself. I think I generally use new when creating instances to be assigned to value using let:

let rnd = new Random()

However, I usually don't use new when creating objects to be used as arguments (e.g. Size or Point in the following example):

let frm = new Form(Size = Size(600, 400))
let gr = frm.CreateGraphics()
gr.FillRectangle(Brushes.Red, Rectangle(Point(0, 0), Point(100, 100)))

Possibly, I also prefer using new for more complicated types and avoid it for simple types or for .NET value types (but I don't think I do this too consistently).

like image 56
Tomas Petricek Avatar answered Dec 19 '22 05:12

Tomas Petricek