Say you have a class for a product (for example a toy) that you are using for a shops application:
class Product
{
string name;
decimal price;
string maker;
//etc...
}
You can define an explicit cast that might do the following:
public static explicit operator string(Product p)
{
return "Product Name: " + p.name + " Price: " + p.price.ToString("C") + " Maker: " + p.maker;
// Or you might just want to return the name.
}
That way when you do something like:
textBox1.Text = (string)myProduct;
It will format the output to what was in the explicit operator for the Product
class.
Do not provide a conversion operator if such conversion is not clearly expected by the end users.
What Microsoft means by this is that if you do provide a conversion operator that you do not return un-expected results. Using the last example of our Product
class, this is something that would return an un-expected result:
public static explicit operator string(Product p)
{
return (p.price * 100).ToString();
//...
}
Obviously no one would actually do this, but if someone else were to use the Product
class and use an explicit string conversion, they would have not expected it to return the price times 100.
Hope this helps!