Saturday, March 3, 2018

Extreme short hand coding (C#, ASP.NET)

I was adding items to a drop down list on code behind and in my quest to reduce lines of code, I did this:

dropdownListOne.Items.Add(New ListItem("text", "value" ) With {.Selected = True})

This would add a new listitem and select it. You can also achieve this by writing the following lines:

Dim li As New ListItem()
li.Text = "text"
li.Value = "value"
li.Selected = True
dropDownListOne.Items.Add(li)

Woohoo! So I just saved 4 lines of code (could be more if we had more properties of ListItem to set). Not much difference in performance, I suppose. You can achieve the same thing in C# using:

dropDownListOne.Items.Add(New ListItem("text", "value") { Selected = true});

No comments:

Post a Comment