The VB.NET 'With' Statement - embrace or avoid?

后端 未结 10 2480
感动是毒
感动是毒 2020-11-29 02:53

At work, I\'m frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sa

10条回答
  •  感动是毒
    2020-11-29 03:06

    AVOID the WITH Block at all costs (even readability). Two reasons:

    1. the Microsoft Documentation about With...End With says that in some circumstances, it creates a copy of the data on the stack, so any changes that you make will be thrown away.
    2. If you use it for LINQ Queries, the lambda results DO NOT Chain and so each intermediate clause's result is thrown away.

    To describe this, we have a (broken) example from a Textbook that my co-worker had to ask the author about (it is indeed incorrect, the Names have been changed to protect... whatever):

    With dbcontext.Blahs
    .OrderBy(Function(currentBlah) currentBlah.LastName)
    .ThenBy(Function(currentBlah) currentBlah.FirstName)
    .Load()
    End With

    The OrderBy and ThenBy have No Effect at all. IF you reformat the code by ONLY dropping the With and End With, and adding line continuation characters at the end of the first three lines... it works (as shown 15 pages later in the same textbook).

    We don't need any more reason to search and destroy WITH Blocks. They only had meaning in an Interpreted framework.

提交回复
热议问题