TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# This Instance

This C# article uses the this-keyword in an example program. The keyword is part of an instance expression.

This, a keyword, eliminates naming conflicts.

It indicates the current instance. Two variables sometimes have the same identifier. This keyword eliminates mistakes—it indicates the class member with the identifier.

Tip: The "this" keyword is part of an instance expression. Please also see "base."

Base

Example. This program shows how to use the "this" keyword when referring to a class instance. It shows that you can use the "this" keyword inside the class declaration only and to refer to that instance.

Static: This cannot refer to a static field or method. It cannot occur inside a static class.

Inferred: The "this" keyword is inferred by the compiler and not required. It is useful for expressing your intent.

C# program that uses this instance expression

using System;

class Perl
{
    public Perl()
    {
	// Call instance method with this.
	this.B();
    }

    int _a; // Instance field

    public void B() // Parameterless instance method
    {
	// Increment instance field without "this".
	_a++;
	// Increment instance field with "this".
	this._a++;
	// Read instance field with "this".
	Console.WriteLine("B called: " + this._a);
    }
}

class Program
{
    static void Main()
    {
	// Create a new instance of the type Perl.
	// ... The constructor calls method B.
	// ... Then we call method B again.
	Perl perl = new Perl();
	perl.B();
    }
}

Output

B called: 2
B called: 4

Instance method. This program demonstrates how you can call an instance method with the "this" instance expression in the C# language. The method B can be called as "this.B()" only if you are inside the class.

Also: If you are external to the class, you can call B as "perl.B()", where "perl" is the instance variable identifier.

The program accesses a field with the instance expression "this". The statements "_a++" and "this._a++" are precisely equivalent in this program. The compiler will automatically resolve the instance expression in each case.

Example 2. There is another way to use the "this" instance expression in a class. We can pass the "this" instance to another method. That method will then receive the reference to the class we called it from.

Tip: This approach can be useful in some contexts where you have a chain of method calls and constructors.

C# program that uses this as argument

using System;

class Net
{
    public string Name { get; set; }
    public Net(Perl perl)
    {
	// Use name from Perl instance.
	this.Name = perl.Name;
    }
}

class Perl
{
    public string Name { get; set; }
    public Perl(string name)
    {
	this.Name = name;
	// Pass this instance as a parameter!
	Net net = new Net(this);
	// The Net instance now has the same name.
	Console.WriteLine(net.Name);
    }
}

class Program
{
    static void Main()
    {
	Perl perl = new Perl("Sam");
    }
}

Output

Sam

Disambiguate. You can also use "this" to disambiguate the variable, for times when you have a conflict in a parameter or local variable name and a field name. This sometimes prevents a compile-time error.

Terms: The term "precisely equivalent" means exactly equal. The term "disambiguate" means to make the difference clear.

Standard. As you read the C# specification, each member type describes its behavior with the "this" keyword as an instance expression. None of the member types allow you to use "this" when dealing with a static declaration.

Note: The standard refers to the "this" keyword as the instance expression. The keyword is an important part of the language.

Expressions: The standard goes to great detail about the nature of expressions in a 150-page chapter. This chapter was not my favorite.

Contexts. There are other contexts and locations where you can use the keyword 'this'. You can use 'this' in a constructor initializer to implement constructor overloading and code sharing. Also, you can use 'this' to declare an indexer.

Constructor Initializer

Tip: An indexer can be accessed with the same syntax as an array type. More details on indexers are available.

Indexer

Extension method syntax uses the "this" keyword in a different context. "This" is used to specify the instance variable in the parameter list of the extension method. The parameter has another formal name.

Extension Method

Summary. We looked at the "this" instance expression in the C# language. We provided details from the C# standard itself. The instance expression is optional in many cases. It indicates exactly which identifier is being referenced.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf