Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When must we use implicit and explicit operators in C#?

What is the usage of these operators?

like image 740
masoud ramezani Avatar asked Mar 03 '10 12:03

masoud ramezani


People also ask

Can you have both implicit and explicit operators in a class?

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?

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.

When should the implicit keyword be used to enable implicit conversions?

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.

What is implicit type casting in C programming?

‘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.


2 Answers

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.

like image 152
Jon Skeet Avatar answered Oct 26 '22 14:10

Jon Skeet


They are used when doing operator overloading. Here's a link to a MSDN article.

like image 32
Richard Nienaber Avatar answered Oct 26 '22 13:10

Richard Nienaber