Should I use new Type() or just Type() for calling

2019-02-12 06:32发布

Both syntaxes are equivalent (at least I suppose they are).

let o1 = new Object()

or

let o2 = Object()

Which way do you use more often? What about readability issues?

3条回答
甜甜的少女心
2楼-- · 2019-02-12 06:43

I feel like omitting "new" is a bit more functional, so that's my preference. I like that you can treat a constructor just like any other function returning an instance of a type.

查看更多
对你真心纯属浪费
3楼-- · 2019-02-12 06:50

They are the same.

I prefer using 'new', with little good reason other than it is what I am accustomed to in other languages, and it makes it easier to findstr/grep for constructor calls (lacking smart tools to 'find all references' in a solution).

查看更多
再贱就再见
4楼-- · 2019-02-12 06:58

I second what kvb says. Additionally, I omit new because this allows me to invoke members directly on the constructed object, just like in C#. For example, the follow code works:

DateTime(2012, 12, 21).ToString()

The following code does not work and results in a compiler error:

new DateTime(2012, 12, 21).ToString()

So now I need to parenthesize the new expression in order to get it to compile:

(new DateTime(2012, 12, 21)).ToString()

I don't like extra parentheses, so I avoid using new now.

The one case where I would still use it is when I am creating an object that implements IDisposable. This is because if I omit the new keyword when creating a IDisposable the F# compiler gives a warning:

let writeFile =
    let writer = StreamWriter(@"hello.txt")
    writer.WriteLine("hello")

Results in this:

warning FS0760: It is recommended that objects that support the IDisposable interface are created using 'new Type(args)' rather than 'Type(args)' to indicate that resources may be owned by the generated value

I can get rid of the warning by adding in the new keyword:

let writeFile =
    let writer = new StreamWriter("hello.txt")
    writer.WriteLine("hello")

The warning also causes me to realize that I should really have a use binding for my IDisposable:

let writeFile =
    use writer = new StreamWriter("hello.txt")
    writer.WriteLine("hello")

But if I wrote my code to use new all the time then I would never get the warning reminding me that I am working with an IDisposable!!!

It also makes for less typing. ;-)

查看更多
登录 后发表回答