Jitesh Byahut 10/4/2014 2046

This Keyword In C#

This keyword refers to current instance of the class. This keyword use to declare indexer and also in extension method.

Call same class property

You can call same class property using this keyword.

// Call class property

class TestClass

{

    string _name, _email;

    public TestClass()

    {

       this._name = "asphelps";  

       this._email = "asp@asphelps.com";

    }

}

Call form's control

You can call page/form tools on code behind page.

//Call tool on page behind

protected void Page_Load(object sender, EventArgs e)

{

    this.TextBox1.Text = "asphelps";

}

 

//Call tool on form behind

public partial class DesktopApplication : Form

{

       

    public DesktopApplication()

    {

        InitializeComponent();

        this.textBox1.Text = "asphelps";           

    }

}

This keyword use in Indexer

public class Students

{

    private string[] str = new string[10];

 

    public string this[int i]

    {

        get

        {

            return str[i];

        }

        set

        {

            str[i] = value;

        }

 

    }

}

This keyword use in Extension method

You can create extension method using this keyword.

public static class ExtensionSquare

{

    public static int Square(this int num)

    {

        return num * num;

    }

}



Please give your feedback for improving this page