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;
}
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.
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.
In C, %n is a special format specifier. In the case of printf() function the %n assign the number of characters printed by printf().
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With