Why isn’t this allowed in VB.NET:
New SqlCommand("some string", someSqlConnection).ExecuteNonQuery()
Why would the language have been designed to require that this be used instead:
Dim com As New SqlCommand("some string", someSqlConnection)
com.ExecuteNonQuery()
It doesn’t seem to me like it would have taken much time at all to implement. Am I wrong? Is there some theoretical advantage this would give a language?
EDIT
Please read: I thought this language feature was not supported in VB.NET. I had forgotten that I had used it in the past, and so when lines like the first one above would break, I did not expect there would be a work-around like in the accepted answer.
…Although, looking back at it again, there seems to be trouble doing this when it’s off by itself on a line of code, and not used as a function argument or something. I bet that’s probably part of why I originally posted this. I wonder why this in particular wouldn’t be allowed, but I’m asking a question on SO to see if there’s a similar work-around for that…
This is not a question about how to use unnamed objects on a single line; this was a question about why a language designer would intentionally choose to forgo such a feature in a language like this. Was there a lingual advantage to not allowing this feature, or would it just take unexpectedly long to implement?
There was a misunderstanding, but that does not change the conceptual nature of the original question, and it does not change the fact that it was searching for a logical reason to omit such a feature.
The bottom line is this: This is a site about “conceptual questions about software development”. This almost immediately implies trace amounts of opinion, subjectiveness, etc – as specifically noted in the very same flag this question was put under. The rule is to not push it too far, and my question did not. Please remove the flag. Thank you.
4
VB does have this functionality, however the syntax is a bit different (obviously) than C#.
Try (New SqlCommand("some string", someSqlConnection)).ExecuteNonQuery()
.
Basically, adding the parenthesis around the instantiation of the object tells it to first create the object, then call the method. The code in the question, on the other hand, is trying to tell it to create an object whose type is SqlCommand("some string", someSqlConnection)).ExecuteNonQuery()
(which obviously isn’t an object type).
0