Anonymous sync syntax - good or bad?

For quick tasks, when I use only one instance of an object, I know that I can do the following:

int FooBarResult = (new Foo()).Bar();

I say this is absolutely acceptable with objects that are not disposable, and more readable than the alternative:

Foo MyOnceUsedFoo = new Foo();
int FooBarResult = MyOnceUsedFoo.Bar();

What are you using and why?
Are you using this type of anonymous instance in a production application?
Preference: with parentheses "(new Foo ()). Bar ();" or without "new Foo (). Bar ();"?

(Edited for an abstract question away from the Random class)

+3
source share
6 answers

: , (new Random().Next(0,100)) . .


, , . , , . ( , , ).

, , (new MyObject().Method() ).

+8

, . , - . , , .

. , , .

- . , .

+6

, .

, , .

, CIL, .

+3

. , .

+1

- , - . - .

+1

, , :

1)

, ,

2) , , .

, , , " ", , , .

As Mehrdad notes, doing this using the Random class is not a good idea.

As he also notes, redundant parentheses make it less concise; if you are not in the dusty corner of a language, assume that competent programmers know the priority of the language operator. In this case, even if I don’t know the priority of the operator, alternative parsing (calling new on the return function) is pointless, so the “obvious” reading is the correct reading.

int RandomIndex = (new Random()).Next(0,100);
int RandomIndex = new Random().Next(0,100);
0
source

Source: https://habr.com/ru/post/1705904/


All Articles