Why thankfully?
It does for Console.WriteLine which takes a string.
Why not for MyOwnFunction which takes a string?
I see no difference between the two.
(I personally was surprised that C# does this at all implicitly, since
it does so much to ensure proper / strict type checking, so I don't
care that I must do astruct.ToString() manually.)
Ok, I don't think you mean using Print(astruct.ToString()), so you
must mean adding such capability to the struct itself, such that I can
do Print(astruct). I'd prefer not to do that anyway. But, why is it
needed? And why is it not recommended?
Just to clear up the final mystery in this thread, an "implicit
conversion" is a static method that you can write as part of your
class or struct that tells the compiler that your type can silently be
converted to some other type.
An example may help. I have written a Fraction struct. It allows me to
represent rational numbers (the company I work for is in the wood
business, so we often have to deal with values like "15 7 / 32" or
"1 / 2"). I have an implicit conversion from Fraction to decimal. This
means that I can do this:
Fraction half = new Fraction(1, 2);
decimal d = half;
On that second line, the compiler invokes my implicit conversion
function to convert the Fraction to a decimal.
You can also write explicit conversions: conversions that require the
programmer to specify an explicit cast. If I had written the Fraction-
to-decimal conversion as explicit, I would be forced to do this:
Fraction half = new Fraction(1, 2);
decimal d = (decimal)half;
You can read more here:
http://msdn2.microsoft.com/en-us/library/85w54y0a(VS.80).aspx
Conversions (explicit and implicit) and operator overloading are best
used sparingly, as they can be horribly abused (as they can be in C++,
too). I tend to restrict mine to structs (value types) and then only
in situations in which (I believe) it will be abundantly clear to the
reader of the code what is going on.
As a counterexample, this:
WarehouseDetail warehouseInfo =
stockItem.GetWarehouseDetail(warehouse);
is much easier to understand than this:
WarehouseDetail warehouseInfo = stockItem + warehouse;
although the latter is simple to achieve with an operator overload.