Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "this" in C#

Tags:

c#

Could anyone please explain the meaning "this" in C#?

Such as:

// complex.cs
using System;

public struct Complex 
{
   public int real;
   public int imaginary;

   public Complex(int real, int imaginary) 
   {
      this.real = real;
      this.imaginary = imaginary;
   }
like image 941
user722784 Avatar asked Jun 07 '11 19:06

user722784


People also ask

What is this operator in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What does ~= mean in C?

The ~ operator in C++ (and other C-like languages like C and Java) performs a bitwise NOT operation - all the 1 bits in the operand are set to 0 and all the 0 bits in the operand are set to 1. In other words, it creates the complement of the original number.

What does %n do in C?

In C, %n is a special format specifier. In the case of printf() function the %n assign the number of characters printed by printf().

What the meaning of == in C example?

The '==' operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example: 5==5 This will return true.


1 Answers

The this keyword is a reference to the current instance of the class.

In your example, this is used to reference the current instance of the class Complex and it removes the ambiguity between int real in the signature of the constructor vs. the public int real; in the class definition.

MSDN has some documentation on this as well which is worth checking out.

Though not directly related to your question, there is another use of this as the first parameter in extension methods. It is used as the first parameter which signifies the instance to use. If one wanted to add a method to the String class you could simple write in any static class

public static string Left(this string input, int length)
{
    // maybe do some error checking if you actually use this
    return input.Substring(0, length); 
}

See also: http://msdn.microsoft.com/en-us/library/bb383977.aspx

like image 111
Nate Avatar answered Sep 29 '22 21:09

Nate