Not true. The truth is a bit more complex than that. .NET provides
When I was talking of casting I was of course only talking about casting
in terms of objects and not of primitive types.
Sorry. I misunderstood, as the OP was giving examples of primitive type
casts. My reply was more directed at the OP than at your post.
I have to say I am not extremely well familiar with C# internals but I
doubt it calls a method for a simple cast. Casting an instance from
object to string will probably only tell the compiler not to report the
typical incompatible types message - along with additional checks for
possible unsupported casting exceptions.
What you say is true for casts up and down the reference type
hierarchy, but not for other kinds of "casts" (which are really
conversions, as you pointed out, but which use the cast notation and
therefore are rightly referred to as "casts").
Casting a reference type to one of its parent types (up the class
hierarchy) or to a child type (down the class hierarchy) does not
involve anonymous instances or any copying at all. It simply, as you
mentioned, copies the reference to a variable of another type. Both
variables continue to point at the same object instance, and will
usually interpret all method calls and property references the same
(unless a method or property is declared "new").
When I was talking about casting to a string (or from a string), I was
not referring to a simple cast down the inheritance hierarchy like
this:
Object o = "abcdef";
string s = (string)o;
which in fact does nothing more than copy the reference to "abcdef"
from o to s, along with the necessary run-time type compatibility
checking. I was, instead, referring to a cast like this:
MyClass mc = new MyClass();
string s = (string)mc;
which in C# is possible if you declare an explicit or implicit cast
operator that casts from MyClass to a string. That "cast" is, in fact,
a call to the static method you declare that performs the conversion.
(If the cast operator is implicit then you can express the second line
like this:
string s = mc;
with no complaint from the compiler. Only explicit casts _require_ the
(string) cast notation.)
Of course, when dealing with built-in primitive types and casts up and
down the class hierarchy the compiler doesn't bother calling a method.
A method call is required only for casts that you define yourself.