Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you control the places where you want to use this "extension operator" (which you normally do with extension methods anyway), you can do something like this:</p> <pre><code>class Program { static void Main(string[] args) { StringBuilder sb = new StringBuilder(); ReceiveImportantMessage(sb); Console.WriteLine(sb.ToString()); } // the important thing is to use StringBuilderWrapper! private static void ReceiveImportantMessage(StringBuilderWrapper sb) { sb += "Hello World!"; } } public class StringBuilderWrapper { public StringBuilderWrapper(StringBuilder sb) { StringBuilder = sb; } public StringBuilder StringBuilder { get; private set; } public static implicit operator StringBuilderWrapper(StringBuilder sb) { return new StringBuilderWrapper(sb); } public static StringBuilderWrapper operator +(StringBuilderWrapper sbw, string s) { sbw.StringBuilder.Append(s); return sbw; } } </code></pre> <p>The <code>StringBuilderWrapper</code> class declares an <a href="http://msdn.microsoft.com/en-us/library/85w54y0a.aspx" rel="noreferrer">implicit conversion operator</a> from a <code>StringBuilder</code> <em>and</em> declares the desired <code>+</code> operator. This way, a <code>StringBuilder</code> can be passed to <code>ReceiveImportantMessage</code>, which will be silently converted to a <code>StringBuilderWrapper</code>, where the <code>+</code> operator can be used.</p> <p>To make this fact more transparent to callers, you can declare <code>ReceiveImportantMessage</code> as taking a <code>StringBuilder</code> and just use code like this:</p> <pre><code> private static void ReceiveImportantMessage(StringBuilder sb) { StringBuilderWrapper sbw = sb; sbw += "Hello World!"; } </code></pre> <p>Or, to use it inline where you're already using a <code>StringBuilder</code>, you can simply do this:</p> <pre><code> StringBuilder sb = new StringBuilder(); StringBuilderWrapper sbw = sb; sbw += "Hello World!"; Console.WriteLine(sb.ToString()); </code></pre> <p>I created <a href="http://codecrafter.blogspot.com/2010/04/more-understandable-icomparable.html" rel="noreferrer">a post</a> about using a similar approach to make <code>IComparable</code> more understandable.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload