Simplest way to reverse a string in C# (in a RichTextBox)

I discovered this way to reverse a string in a RichTextBox in C# accidentally. I am not sure if it is a bug or some kind of behaviour that will not work in other versions of .NET (I did this in 1.1), but here is what you can try:

  1. Create a Windows Forms application.
  2. Drag a RichTextBox onto the form.
  3. Remove all text from the RichTextBox
  4. Register the KeyPress event of the RichTextBox
  5. Put this line in the event function:
    richTextBox1.Text = richTextBox1.Text;
  6. Compile and type away in your RichTextBox.

I think this is really weirdish yet a little bit fascinating :) I figure presenting a teacher at school with this might cause some confusion. I am sure it would have if my C# class where writing an application that reverses the users input was one of the first simple exercises. Usually one would use a loop or similar.

If you were not able to follow the instructions above, see the full source code below.

using System;
using System.Windows.Forms;

namespace ReverseString
{
  public class Form1 : System.Windows.Forms.Form
   {
      private System.Windows.Forms.RichTextBox richTextBox1;
      private System.ComponentModel.Container components = null;

      public Form1()
      {
         InitializeComponent();
      }

      private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
      {
         richTextBox1.Text = richTextBox1.Text;
      }

      protected override void Dispose( bool disposing )
      {
         if( disposing )
         {
            if (components != null)
            {
               components.Dispose();
            }
         }
         base.Dispose( disposing );
      }

      #region Vom Windows Form-Designer generierter Code
      /// 
      /// Erforderliche Methode für die Designerunterstützung.
      /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
      /// 
      private void InitializeComponent()
      {
         this.richTextBox1 = new System.Windows.Forms.RichTextBox();
         this.SuspendLayout();
         //
         // richTextBox1
         //
         this.richTextBox1.Location = new System.Drawing.Point(8, 8);
         this.richTextBox1.Name = “richTextBox1″;
         this.richTextBox1.Size = new System.Drawing.Size(280, 264);
         this.richTextBox1.TabIndex = 0;
         this.richTextBox1.Text = “”;
         this.richTextBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.richTextBox1_KeyPress);
         //
         // Form1
         //
         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
         this.ClientSize = new System.Drawing.Size(292, 273);
         this.Controls.Add(this.richTextBox1);
         this.Name = “Form1″;
         this.Text = “Form1″;
         this.ResumeLayout(false);
      }
      #endregion

      [STAThread]
      static void Main()
      {
          Application.Run(new Form1());
      }
   }
}

About this entry