Monday, June 28, 2010

C# tip - 6/28/2010 (last one for today)

Use foreach loops.

Here's why:

  • efficiency => the compiler picks the most efficient loop implementation depending on the data collection being looped
  • ease of use => it's very simple to change the collection instantiation without changing the foreach loop.
private Square[] _board  = new Square[8];
foreach(Square _sq in _board);
===============================

private Square[] _board  = new Square[10];
foreach(Square _sq in _board);//will work without the need to change anything
===============================
private Square[,] _board = new Square[10,10];
foreach(Square _sq in _board);//will still work without the need to change anything
===============================
private Square[,,] _board = new Square[10,10,10];
foreach(Square _sq in _board);//will still work without the need to change anything



No comments:

Labels