Daniel Lip
Daniel Lip

Reputation: 11325

Why this function must be static?

public void AppendText(this RichTextBox box, string text, Color color)
{
    box.SelectionStart = box.TextLength;
    box.SelectionLength = 0;

    box.SelectionColor = color;
    box.AppendText(text);
    box.SelectionColor = box.ForeColor;
} 

It was public static void

But then i had an error on this line in my Form1:

public partial class Form1 : Form

The error is on the Form1 say:

Error Extension method must be defined in a non-generic static class

If i remove the static from the function im getting error on the AppendText say:

Error Extension method must be static

How do i work with that ?

Upvotes: 2

Views: 1056

Answers (2)

Habib
Habib

Reputation: 223322

Because its an extension method on RichTextBox, it needs to be static, also it needs to be inside a static class.

this keyword in method parameters is defining it as an extension method on RichTextBox

AppendText(this RichTextBox box.......

From MSDN - Extension Methods

Extension methods are defined as static methods but are called by using instance method syntax.Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier.

From MSDN - this keyword

The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

if you want to create an extension method on RichTextBox, then you can have to define this method as static and also have it in a static non-generic class something like:

public static class MyExtensions
{
   public static void AppendText(this RichTextBox box, string text, Color color)
   {
    box.SelectionStart = box.TextLength;
    box.SelectionLength = 0;

    box.SelectionColor = color;
    box.AppendText(text);
    box.SelectionColor = box.ForeColor;
   } 
}

later you can call it like:

RichTextBox yourRichTextBox = new RichTextBox();
yourRichTextBox.AppendText("Some Text",Color.Blue);

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838806

The presence of the this keyword before the first parameter is for defining extension methods.

public void AppendText(this RichTextBox box, string text, Color color)
//                     ^^^^

Extension methods must be inside a static class.

Remove the this keyword to make it into an ordinary method.

Upvotes: 2

Related Questions