Share via


Req26: allow With as a modifier on expressions

[This post is part of a series, "wish-list for future versions of VB"]

 

IDEA: We should allow "With" as a modifier on expressions. Currently the "With" object-initializer syntax is only allowed on constructors, e.g.

Dim x = New S With {.p = 1, .q = 2}

This is rather limiting. It would be good if we could use it on factory methods, e.g.

Dim y = Factory.CreateThing() With {.p = 1, .q = 2}

The cleanest way to allow this, in the language, is to allow a "With" initializer to come after any expression:

Expression ::= ... | Expression ObjectMemberInitializer

This would be syntactic sugar for evaluating the expression and then assigning its properties:

Dim $temp = Factory.CreateThing()

$temp.p = 1

$temp.q = 2

Dim y = $temp

 

 

Provisional evaluation from VB team: When you tell the car dealer "I'd like to buy this car but with the yellow paintjob" -- you don't expect him to get out his spraycan and change this car right here; you expect him to go to the back of the store and pick out a similar car but with one difference. Likewise, we think it will be awfully unclear to users that "With" modifies an existing object rather than constructing a new object with some variations. We think that this proposal "digs up more snakes than ladders".

Comments

  • Anonymous
    March 04, 2010
    You could add an inline version of the with block to get ALMOST the desired thing, without any danger of confusion: Dim y = Factory.CreateThing() With y {.p = 1, .q = 2} It would be an inline version of this: Dim y = Factory.CreateThing() With y  .p = 1  .q = 2 End With

  • Anonymous
    March 05, 2010
    That seems like a misleading analogy to me.  Cars work like that because painting a car is a major undertaking.  If the dealer could just type car.color = yellow then this probably IS the way it would work.   I guess I don't really feel a difference between turning a brand new object yellow and turning an object with some non-default properties yellow. Also, With already has a meaning along these lines: Dim y As New Car() '...other code With y  y.color = yellow End With Here, you ARE modifying an existing object via With.

  • Anonymous
    March 05, 2010
    HELP I HAVE WINDOWS SPEECH AND DRAGON 10 ON MY COM I AM HOPEING SOMEONE OUT THERE CAN HELP ME, CAN I TRANSCRIBE MY WAV RECORDINGS INTO A WORD DOC THESE ARE PUBLIC TALKS WHICH I RECORD FOR THOSE WHO ARE HARD OF HEARING AND I AM HOPEING THAT THIS WOULD BE ANOTHER WAY TO HELP THEM AS READING WOULD ALSO HELP

  • Anonymous
    March 07, 2010
    This link will show you how to transcribe a recording with Dragon: http://wiki.wsu.edu/ctowiki/Transcribing_a_recording_with_Dragon_Naturally_Speaking

  • Anonymous
    March 29, 2010
    I don't regard this as a major necessity, but I also don't agree that the syntax is confusing.  I think it's perfectly clear.  More syntactic sugar never hurts as long as it's clear what it means.