Reputation: 4409
How to optimise if else condition for tableview cell color
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath){
var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell;
if (cell == null)
cell = new TableCell ();
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
if (indexPath.Row % 2 == 0) {
cell.BackgroundColor = UIColor.White;
} else {
cell.BackgroundColor = UIColor.LightGray;
}}
Upvotes: 1
Views: 559
Reputation: 5234
You can also use ?? for the cell creation:
var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell ?? new TableCell();
From the looks of it this might also be a slight improvement as the Accessory seems to be a static type and doesn't need to be assigned every single time:
var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell
?? new TableCell() { Accessory = UITableViewCellAccessory.DisclosureIndicator };
Upvotes: 0
Reputation: 726929
There is little here left to be optimized. The only thing I'd change is the last if
- I'd replace it with a conditional expression:
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath){
var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell;
if (cell == null) {
cell = new TableCell ();
}
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
cell.BackgroundColor = (indexPath.Row % 2 == 0) ? UIColor.White : UIColor.LightGray;
}
This is a matter of personal preference, though: your if
statement with two assignments was perfectly readable too.
Upvotes: 3