You can manually override the implicit and explicit cast operators for a class. Tutorial here. I'd argue it's poor design most of the time, though. I'd say it's easier to see what's going on if you wrote
string b = a.ToHtml();
But it's certainly possible...
public class A
{
public string Content { get; set; }
public static implicit operator string(A obj)
{
return string.Concat("<span>", obj.Content, "</span>");
}
}
To give an example of why I do not recommend this, consider the following:
var myHtml = "<h1>" + myA + "</h1>";
The above will, yield "<h1><span>Hello World!</span></h1>"
Now, some other developer comes along and thinks that the code above looks poor, and re-formats it into the following:
var myHtml = string.Format("<h1>{0}</h1>", myA);
But string.Format
internally calls ToString
for every argument it receives, so we're no longer dealing with an implicit cast, and as a result, the other developer will have changed the outcome to something like "<h1>myNamespace.A</h1>"