s26f84

hey all,

Just a quick question about casting and how it works. if is do String s = (string)someobject, what happens in the background i.e. some method is invoked intternally to convert the object to a string or what How does this work I tried to find the answer but no luck. Please help .

Thanks

sunny




Re: Visual C# Language casting

frederikm

Hi

it's not some hidden method...

i'll try to give you an explanation that's not really technical but which can give you an idea of what i mean :)

at runtime the type of the object is known...

the object in itself is accessed via a "type interface" (interface meaning the collection of methods, properties, etc; this is not the c# interface)
which specifies what methods, properties and so on you can access on the object

casting would be changing the "type interface" with which you access the object.

the InvalidCastException would be when you try to put a "type interface" on an object which does not match the type.

Hope this helps you out...

If you can't make heads or tails of this, or you would like to get the real technical explanation, let me know ;-)






Re: Visual C# Language casting

Figo Fei - MSFT

Hi,

Actually, the C# compiler will not let "someobject" cast into string, unless someobject is an instance of compatible type (string or types derived from string).

Here is more knowledge about casting: http://msdn2.microsoft.com/en-us/library/ms173105.aspx

Thank you