Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use this keyword as function argument [duplicate]

Possible Duplicate:
What does “this” mean in a static method declaration?

i go through a code snippet and found this keyword is used as function argument. the code snippet is like

public static void AddCell(this Table table, object cell) 

why AddCell has this keyword they can write likeAddCell(Table table, object cell)

please explain the situation when to use this keyword as function argument with small code sample as a result i can better understand. thanks.

like image 840
Thomas Avatar asked Dec 09 '25 22:12

Thomas


2 Answers

Basically what is being defined in your example is an extension method. In a static method, if you define the first argument using the this keyword you are allowing the method to be called on instance objects of the type defined on the first argument.

In the example you stated you would be able to do something like this:

Table someTableInstance; /// must be instanciated somehow;
someTableInstance.AddCell(cell); // Call the AddCell method as if it was an instance method.

Hope it helps, Regards, Bruno

like image 104
Bruno Avatar answered Dec 11 '25 12:12

Bruno


This syntax is used for extension methods.

These look a bit odd when you first see them written, but they are fabulous things - most of Linq is written as extension methods.

Here's a good intro tutorial - http://csharp.net-tutorials.com/csharp-3.0/extension-methods/ - which includes the example:

public static class MyExtensionMethods
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

which enables you to call:

"fred".IsNumeric()
like image 41
Stuart Avatar answered Dec 11 '25 10:12

Stuart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!