Ccrewriter Error: Unable to cast object...

by Larry Spencer Wednesday, August 24, 2011 2:25 PM

I got a strange error today. Google didn't turn up any solution, so I thought I'd post the solution here.

My task was to write some code contracts. Many of the contracts use the same error message so I got the bright idea of putting the message in a static member variable, thus:

static string _errorMessage = "Type must be null or an interface.";

public void MyMethod(Type contractType)
{
  Contract.Requires(
    contractType == null || contractType.IsInterface,
    _errorMessage);
  // ...etc...
}

That brought on this mysterious error when I compiled:

ccrewrite : error : Unable to cast object of type 'System.Compiler.Method' to type 'System.Compiler.Field'.

However, when I made the message a literal in each Contract.Requires call (ugh!), all was well:

 

public void MyMethod(Type contractType)
{
  Contract.Requires(
    contractType == null || contractType.IsInterface,
    "Type must be null or an interface.");
  // ...etc...
}

I was using Visual Studio 2010 and .NET 4.0.

If you know why Contract.Requires isn't happy with a static string, please comment. In the meantime, I hope this post helps someone resolve the error.

Tags:

All | General

Comments (1) -

11/16/2011 10:47:07 AM #

I got the same problem trying to use static readonly DateTime and double values in code contracts. You might be interested to know that the number of Google hits on this error message has gone up from zero (when you searched) to one: your post.

The build worked once I moved the readonly fields to a separate static class. Thanks for giving me enough to go on to find a solution.

Matthew Strawbridge United Kingdom

Add comment

About the Author

Larry Spencer

Larry Spencer develops software with the Microsoft .NET Framework for ScerIS, a document-management company in Sudbury, MA.