Implicit casting of generic classes

Can anyone tell me what am I missing here? Here’s a simple class

public class Mock<TType>

{

    private readonly TType _actual;

 

    public Mock(TType actual)

    {

        _actual = actual;

    }

    public TType Actual

    {

        get { return _actual; }

    }

    public static implicit operator TType(Mock<TType> item)

    {

        return item.Actual;

    }

}

That’s a generic class that defines implicit casting operator to it’s generic parameter, no magic here. The code compiles without warning. Methods like this one:

 

public TType ThisWorks<TType>()

{

    return new Mock<TType>(default(TType));

}

work as well.

What’s even more stunning, whereas this works:

Mock<string> mock1 = _mocks.Mock<string>();

string actual1 = mock1;

This doesn’t:

Mock<ISomethingUseful> mock2 = _mocks.Mock<ISomethingUseful>();

ISomethingUseful actual2 = mock2;

producing error message:

Error    1    Cannot implicitly convert type ‘Mocks.Mock<Mocks.ISomethingUseful>’ to ‘Mocks.ISomethingUseful’. An explicit conversion exists (are you missing a cast?)

Am I missing something here? Why does it say ‘explicit conversion exists’ when I created implicit conversion? Why it doesn’t work for the interface when it works for string?

[UPDATE:]

According to chapter 6.4.4 of C# 3.0 Language specification you just can’t have implicit conversion to an interface. This in yet another time when I hit an invisible wall trying to do something with generics…

And if you thought that

public class MyClass<TType>:TType

{

}

could be a solution: it isn’t – this won’t compile as well.

Technorati Tags: ,
  • Gauthier Segay

    MyClass:TType

    c# ain’t c++ 😉