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

About the Author

Larry Spencer

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