Why is the implicit operator so limited on C#?


Does anyone knows why the implicit operator is so limited? You can use if for interfaces, for instance.
I had this big idea of IoC with generics that would look like:

IEmail email = new IoC<Email>();

But you just can't do that with the implicit operator, and using the explicit one kind of ruins the whole fun, not to mention that it produce cast driven code.

Print | posted on Tuesday, January 03, 2006 4:24 PM

Feedback


Gravatar

#  1/4/2006 12:52 AM Matthijs van der Vleuten

I cannot reproduce the behavior you're referring to. The following code compiles successfully: (Replace { and } by the less-than and greater-than signs - your blog does not allow these characters.)

internal sealed class IoC{T} where T : new()
{
public static implicit operator T(IoC{T} input)
{
return new T();
}
}

internal static class Program
{
private static void Main()
{
StringBuilder sb = new IoC{StringBuilder}();
Debug.WriteLine(sb.GetType());
}
}


Gravatar

#  1/5/2006 9:00 AM Wesner Moise

(1) There is an ambiguity between a standard interface lookup and an user-defined interface cast. A derived class, for example, may defined an interface for which an user-defined interface conversion already exists.

(2) Interface instances are supposed to be referentially identical to the original object. This breaks with user-defined interface conversion.


Gravatar

#  1/5/2006 1:40 PM Ayende Rahien

I can understand both reasons, but this means that you can't use conversion operator for interfaces at all.
This is sad because it makes it hard to make use of implicit interfaces transperantly.

Comments have been closed on this topic.