If I make an empty test class:
public class Foo
{
}
And I try to compile code with this statement:
Foo foo = "test";
Then I get this error as expected:
Cannot implicitly convert type ‘string’ to ‘ConsoleApplication1.Foo’
However, if I change the declaration of Foo from class to interface, the error changes to this (emphasis mine):
Cannot implicitly convert type
‘string’ to ‘ConsoleApplication1.Foo’.
An explicit conversion exists (are you
missing a cast?)
What is this “explicit conversion” which is supposed to exist?
update: the issue is a bit more subtle than I initially thought. To reproduce it, put this code in a new console application in Visual Studio 2008:
namespace ConsoleApplication1
{
class Foo
{
}
interface IFoo
{
}
class Program
{
static void Main(string[] args)
{
Foo b = "hello";
}
}
}
Visual studio will automatically show the correct error at this point (before you build the code). Now insert the “I” to turn “Foo” into “IFoo” and wait a few seconds without building. The “explicit conversion exists” version of the error will now appear automatically in the error output window and in the tool tip for the assignment error.
The erroneous error then disappears again when you explicitly hit F6 to build.
I am unable to reproduce the reported behaviour. If it does in fact reproduce, that’s a bug. There is no explicit conversion from string to any user-defined interface.
Please update the question with the version number of the compiler you’re using and a small program that reproduces the problem, and I’ll get a bug entered into the bug database.
Thanks!
UPDATE: Apparently it does not reproduce on the command line, but is alleged to reproduce in VS2008.
I am unable to reproduce it in the RC build of VS2010, so if this was in fact a bug in VS2008, it’s probably been fixed. I don’t have an installation of VS2008 handy right now to test unfortunately.
Regardless, if you’re seeing that diagnostic then odds are very good it is simply a bug in the error reporting heuristics in the semantic analyzer. Clearly there is no explicit conversion from string to IFoo.
There is an explicit conversion from any unsealed type to any interface type because there could be a derived type which implements the interface. But string is sealed, so the error should simply be “no conversion”.