Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the "this" keyword be used with value types?

Tags:

c#

.net

I noticed this interesting use of the "this" keyword while viewing the disassembled code of Int32.GetHashCode() in .NET Reflector:

public override int GetHashCode()
{
    return this;
}

I always thought "this" is only used with reference types not value types. In the code above, will boxing be used every time you try to get the hash code of an int?

From the documentation of the "this" keyword in MSDN: - The this keyword refers to the current instance of the class

Regards

like image 769
Waleed Eissa Avatar asked Feb 18 '09 20:02

Waleed Eissa


1 Answers

Yes, this is valid for value types. It does not lead to boxing. While it references the value-type, it is not a reference in the same vein as reference-type references - it is a compile/development time convenience rather than a runtime reference.

Section 7.5.7 of the C# Specification states:

  • When this is used in a primary-expression within an instance constructor of a struct, it is classified as a variable. The type of the variable is the instance type (§10.3.1) of the struct within which the usage occurs, and the variable represents the struct being constructed. The this variable of an instance constructor of a struct behaves exactly the same as an out parameter of the struct type—in particular, this means that the variable must be definitely assigned in every execution path of the instance constructor.

  • When this is used in a primary-expression within an instance method or instance accessor of a struct, it is classified as a variable. The type of the variable is the instance type (§10.3.1) of the struct within which the usage occurs.
    • If the method or accessor is not an iterator (§10.14), the this variable represents the struct for which the method or accessor was invoked, and behaves exactly the same as a ref parameter of the struct type.
    • If the method or accessor is an iterator, the this variable represents a copy of the struct for which the method or accessor was invoked, and behaves exactly the same as a value parameter of the struct type.
like image 129
Jeff Yates Avatar answered Nov 13 '22 13:11

Jeff Yates