Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does casting work?

Tags:

c#

casting

I was wondering what C# does when you for example cast an object to an int.

object o = 10;
int i = (int) o;

Much appreciated :)!

like image 427
Kevin Avatar asked Nov 12 '10 11:11

Kevin


People also ask

How does casting to a device work?

When 'casting' to another device, such as a Chromecast or Apple TV, that device takes over the job of showing videos, photos or music. It's as if your phone or tablet tells the Chromecast what to do, and then the Chromecast goes ahead and does the legwork while the device you're casting from acts as a remote control.

What is the difference between screen mirroring and casting?

Screen mirroring involves sending what's on your computer screen to a TV or projector via a cable or wireless connection. Casting refers to receiving online content via a digital media player to a TV, projector, or monitor via a wireless connection.

Does casting to TV use Wi-Fi or Bluetooth?

Screen mirroring that uses wireless display technology like Miracast actually creates a direct wireless connection between the sending device and the receiving device. Therefore, no Wi-Fi or internet connection is required to mirror your phone screen onto your smart TV.


1 Answers

In the general case, that is a tricky one ;p It depends on the exact scenari:

  • (when the target is a value-type) if the source value is only known as object, it is an unbox operation, which reverses the special way in which value-types can be stored in an object reference (Unbox / Unbox_Any)
  • if the source type is a Nullable<int>, then the .Value property is evaluated (which can cause an exception if the value is empty)
  • if the source type is one of a few built-in types documented in the spec (uint, float, etc), then the specific opcode (which may be nothing at all) is emitted to perform the conversion directly in IL (Conv_I4)
  • if the source type has a custom implicit or explicit conversion operator defined (matching the target type), then that operator is invoked as a static method (Call)
  • (in the case of reference types) if it isn't obviously always untrue (different hierarchies), then a reference cast/check is performed (CastClass)
  • otherwise the compiler treats it as an error

I think that is fairly complete?

like image 121
Marc Gravell Avatar answered Nov 15 '22 20:11

Marc Gravell