1

It seems that CodeContract from DevLab is a nice tool, but I had two errors in with code:

public class SomeClass
{
   private DataTable _dataTable

   // I don't want to write the same condition more then ones, so incapsulate it
   private void CheckRowIndex(int rowIndex)
   {
      //Error1 in next line: User message to contract call can only be string literal, or a static
      // field, or static property that is at least internally visible.    
      Contract.Requires<IndexOutOfRangeException>(_dataTable.Rows.Count >= rowIndex + 1,
        String.Format("There is no row with index {0} in table.", rowIndex));
   }

   public object GetObject(int rowIndex, int colIndex)
   {
     // Error2 in next line: malformed contract
     CheckRowIndex();
     return _dataTable.Rows[rowIndex][colIndex];
   }
   public object GetObject(int rowIndex, string colName)
   {
     CheckRowIndex();
     return _dataTable.Rows[rowIndex][colName];
   }
}

Are there any techniques how to avoid it?

mnsasha
  • 27
  • 4

1 Answers1

1

For point #1 have a look here

Contract overloads taking a userMessage such as Requires(bool condition, string userMessage) require that the userMessage message be a literal, or static (e.g. static readonly), or const, as per the error message.

Since the user message is for you, the developer, not for users why not just make it generic:

String.Format("There is no row with this index in the table");

There's more of a discussion on what to put in the (IMO badly named) userMessage parameter here

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285