You can replace VB.Net's With
by creating a quick single-letter variable name. It's actually less code, since With
also requires an End With
later on.
For example, one thing I used to need to do fairly often was iterate over the rows in a datatable for a control/break style report.
In vb.net, that might look like this:
Dim CurCustomerName As String
Dim CustomerSalesTotal As Decimal
Dim ds As DataSet = GetReportData()
With ds.Tables(0).Rows
Dim i As Integer = 0
While i < .Count
''//{
CurCustomerName = .Item(i)("CustName")
CustomerSalesTotal = 0
PrintHeaderLine(CurCustomerName)
While i < .Count AndAlso CurCustomerName = .Item(i)("CustName")
''//{
PrintItemLine(.Item(i)("OrderTotal"))
CustomerSalesTotal += .Item(i)("OrderTotal")
i+= 1
End While ''//}
PrintSubTotalLine(CustomerSalesTotal)
End While ''//}
End With
The C# would look like this:
string CurCustomerName;
Decimal CustomerSalesTotal;
DataSet ds = GetReportData();
DataRowCollection r = ds.Tables[0].Rows;
int i=0;
while (i<r.Count)
{
CurCustomerName = r[i]["CustName"];
CustomerSalesTotal = 0;
PrintHeaderLine(CurCustomerName);
while (i<r.Count && CurCustomerName == r[i]["CustName"])
{
PrintItemLine(r[i]["OrderTotal"]);
CustomerSalesTotal += r[i]["OrderTotal"];
i++;
}
PrintSubTotalLine(CustomerSalesTotal);
}
The thing to notice here is that the C# version actually needed less typing, because the VB couldn't combine WITH
with the array index, and had to go through the .Item
property for certain things. It's not a big deal here, but imagine if the report had 20 fields instead of 2 and had to break on 3 items instead of 1.
Of course, you could use the technique demonstrated in C# for VB as well. But the main thing to note is that WITH
doesn't really give you much.