What is the usage of these operators?
Note you cannot have both implicit and explicit operators defined in a class. If you have defined an implicit operator, you will be able to convert objects both implicitly and explicitly. However, if you have defined an explicit operator, you will be able to convert objects explicitly only.
What are implicit and explicit type conversions in C language? Converting one data type into another data type is called type conversions. The compiler provides implicit type conversions when operands are of different data types.
Amount cannot be converted in to Money; therefore, we need explicit casting. So as to summarize, the implicit keyword should be used to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.
‘C’ programming provides another way of typecasting which is explicit type casting. In implicit type conversion, the data type is converted automatically. There are some scenarios in which we may have to force type conversion. Suppose we have a variable div that stores the division of two operands which are declared as an int data type.
Basically when you want to provide conversions between types. LINQ to XML provides good examples... There's an implicit conversion from string to XName, so you can write:
XName name = "element";
but there's an explicit conversion from XAttribute
to int
(and many other types) so you have to include a cast in your code:
int value = (int) element.Attribute("age");
Think very carefully before providing implicit conversions - they're rarely a good idea; LINQ to XML uses them to great effect, but they can be confusing. Even explicit user-defined conversions can surprise the unwary reader.
They are used when doing operator overloading. Here's a link to a MSDN article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With