[Mono-list] implicit, explicit, and why does C# have these?

David La Motta dlamotta@email.com
Thu, 16 Oct 2003 16:52:53 -0400

So I was reading my "C# for Java Developers" book and I came across the 
implicit and explicit operators.  Java doesn't have these but a friend 
suggests C++ does.  Being that I am not a C++ developer I really can't 
comment much on it, except to say that it looks like C# just decided to 
copy functionality from C++, just because it is a "cute" feature of the 
language.  I also can't quite put my finger on the difference between 
implicit and explicit, so if anybody has any insight on these, please, 
do share.

It seems to me that explicit is used when you want to force your API 
clients to use a cast when dealing with different types.  So lets say 
that I have:

public static implicit operator Foo(Bar bar) {...}    and I also have a 
method called
public Foo morph(Foo foo) {...}

If I was ever to use my morph method with a Bar, I could issue the call 

Bar bee = new Bee();
Foo faa = morph(bee);

And the compiler would be happy.  If I was to change implicit for 
explicit in the operator's declaration, the way of calling the method 
would be:

Foo faa = morph((Foo) bee);   // with explicit cast

Is this it, or is there more to it than this?  I also am aware that this 
isn't really a "mono" question per se, but I thought some of you would 
be willing to shed some light on the topic...  :-)


// David