Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow my class to be implicitly converted to a string in C#?

Here's what I want to do...

public class A
{
    public string Content { get; set; }
}

A a = new A();
a.Content = "Hello world!";
string b = a; // b now equals "<span>Hello world!</span>"

So I want to control how a is converted into a String… somehow…

like image 425
jedmao Avatar asked Nov 28 '22 19:11

jedmao


1 Answers

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>"

like image 181
David Hedlund Avatar answered Feb 09 '23 01:02

David Hedlund