Why can't I use the “new” expression as an expression in VB.NET?

Why can't I start a string using brackets followed by the new keyword? For instance:

(New <custom_obj>).foo(var) 

In this case, it is obvious that I am trying to avoid creating a named instance of <custom_obj> because I know that I will use it only in this sentence.

Note that actually creating a named instance is not a problem for me ... I just want to know the reason why this is not possible.

+4
source share
1 answer

Do you want the language responder to respond? Look in the VB.NET Language Specifications, starting with 10. Statements . The simplest answer is that the word “expression” does not appear on this page. NewExpression is clearly different from InvocationExpression, so you can use InvocationExpression in InvocationStatement, but you can only use the new expression in LocalDeclarationStatement or in the context of some larger expression.

More conveniently, the VB.NET syntax is designed to be easy to read, write, and parse, and one way to achieve it is to be careful about what the expression is and what the expression is. Python is similar - assignment is an expression, not an expression. There is no reason for every language to be exactly like C.

But, as civility indicates, you can get around this with the Call statement:

 call new object.toString 

will compile successfully. Try making your classes meaningful instead.

+4
source

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


All Articles