Chapter 23. User-defined conversions/casts

Here is another C# feature which adds to convenience for C# developers but which can be imitated using normal methods.

A user-defined conversion is a custom-made cast from one class to another. So far, type casting has been performed only if the object being cast is a subclass of the other. User-defined conversions allow you to perform casting of one type into an unrelated type. It also gives you the choice of what you want to do when performing the cast.

Sounds difficult? Study this example first.

 1: class Inch{ 2: public float InchValue; 3: 4: public Inch (float value){ // constructor 5: InchValue = value; 6: } 7: } 8: 9: class Cm { 10: public float CmValue; 11: 12: public Cm (float value){ // constructor ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.