Piotr Kula
Piotr Kula

Reputation: 9841

Reducing .Net code using Inline Object creation

I have managed to crunch down a several line code to this

For Each gal In galleries
   With New HtmlGenericControl("div")
                .ID = gal.Header
                .Controls.Add(New HtmlImage() With {.Src = "http://p.com/pic.jpg"})

                galleryContent.Controls.Add(**Me**)
   End With
Next

I cannot find any where how to reference back to the object i am currently working with to add the control back to 'galleryContent' - Using plain me crashes the whole web server... whooops.

Using does not offer the shorter hand of just using . - But it Using the only way to do it? I was sersiosly expecting some kind of .Me or something like this

Any ideas?

Upvotes: 0

Views: 4314

Answers (3)

Jason Larke
Jason Larke

Reputation: 5609

You can do something like:

For Each gal in galleries
    galleryContent.Controls.Add(New HtmlGenericControl("div") With { .ID = gal.Header })
    galleryContent.Controls[galleryContent.Controls.Count - 1].Controls.Add(New HtmlImage() With {.Src = "http://p.com/pic.jpg"})
Next

But this is purely for line-reduction. It severely reduces readability so in any normal scenario you shouldn't be aiming to just cut down on lines of code. Readability is far more important than "line-efficiency".

Upvotes: 1

Sebastian Siek
Sebastian Siek

Reputation: 2075

Mystere Man's is right, but think about that.... that will affect the code readability.

"Code is read much more often than it is written, so plan accordingly"

I would suggest to avoid using "With" in VB ... unless you really "have to".

Hope it helps.

Upvotes: 2

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

You can't. At least not that way.

Try this:

For Each gal In galleries 
   Dim obj as New HtmlGenericControl("div") 
   With obj
        .ID = gal.Header 
        .Controls.Add(New HtmlImage() With {.Src = "http://p.com/pic.jpg"}) 

        galleryContent.Controls.Add(ojb) 
   End With 
Next 

Upvotes: 5

Related Questions